20. 有效的括号_字符串_简单
这道题的思路就是使用栈来进行解决或者使用字符串操作来进行处理
package com.bupt; import java.util.*; public class T20 { public boolean isValid(String s){ while (s.contains("{}") || s.contains("()") || s.contains("[]")){ s = s.replace("{}",""); s = s.replace("()",""); s = s.replace("[]",""); } return s.length()==0; } public boolean isValid(String str){ Stack<Character> stack = new Stack<>(); for (int i = 0; i < str.length(); i++) { if(i==1) { System.out.println(System.identityHashCode(stack.peek()+""+str.charAt(i))); System.out.println(System.identityHashCode("{}")); } if (stack.isEmpty()){ stack.push(str.charAt(i)); } else if((stack.peek()+""+str.charAt(i)).equals("{}") ||(stack.peek()+""+str.charAt(i)).equals("[]") || (stack.peek()+""+str.charAt(i)).equals("()")){ // System.out.println(stack.peek()+""+str.charAt(i)); stack.pop(); }else{ stack.push(str.charAt(i)); } } return stack.isEmpty(); } public static void main(String[] args) { String a = "{}"; System.out.println(a=="{}"); System.out.println('{'+""+'}' == "{}"); Scanner scanner = new Scanner(System.in); while (true){ String str = scanner.next(); boolean valid = new T20().isValid1(str); // System.out.println(valid); } } }
作者:你的雷哥
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面给出原文连接,否则保留追究法律责任的权利。