The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
这是一道匹配题,最简单的方式就是用栈来做了,JAVA中有Strack类,所以直接用就可以了。
public boolean isValid(String s) { boolean result = false; List<Character> ls = new ArrayList<Character>(); if(s == null || s.length()<2){ return false; } char[] chs = {'(',')','[',']','{','}'}; for(char c : chs){ ls.add(c); } Stack<Character> st = new Stack<Character>(); for(int i = 0 ;i<s.length();i++){ if(ls.contains(s.charAt(i))){ if(st.isEmpty()){ st.push(s.charAt(i)); }else{ /*System.out.println((char)st.peek()); System.out.println(s.charAt(i)); System.out.println((char)st.peek()+s.charAt(i));*/ if((char)st.peek()+s.charAt(i) == 81 || (char)st.peek()+s.charAt(i) == 248 ||(char)st.peek()+s.charAt(i) == 184){ st.pop(); }else{ st.push(s.charAt(i)); } } } } if(st.isEmpty()){ result = true; }else{ result = false; } return result; }