【题目】
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
【解析】
就是() {} [] 要成对的出现,比如( { [ ] } )等。
【代码】
public class Solution { public boolean isValid(String s) { char[] stack = new char[s.length()]; int head = 0; char[] cs = s.toCharArray(); for(int i=0;i<cs.length;i++){ switch(cs[i]) { case '{': case '[': case '(': stack[head] = cs[i];
head++; break; case '}': if(head == 0 || stack[head-1] != '{') return false; head--; break; case ')': if(head == 0 || stack[head-1] != '(') return false; head--; break; case ']': if(head == 0 || stack[head-1] != '[') return false; head--; break; } } return head == 0; } }