[LeetCode] NO. 20 Valid Parentheses
[题目] 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.
[题目解析] 该题目判断括号的合法性,可以用stack来解决,stack是先入后出的结构,每次遇到右半边括号的时候,确保pop出来的是对应的左半边括号,遍历结束后,stack为空说明合法,如果非空说明没有匹配。注意监测非法字符。代码如下。
1 public boolean isValid(String s) { 2 if(null == s || 0 == s.length() || 1 == s.length()) return false; 3 Stack<Character> stack = new Stack<Character>(); 4 for(int idx = 0; idx < s.length(); idx++){ 5 char ch = s.charAt(idx); 6 if(ch == '(' || ch == '{' || ch == '['){ 7 stack.push(ch); 8 }else if(ch == ')'){ 9 if(stack.isEmpty() || stack.pop() != '(') return false; 10 }else if(ch == ']'){ 11 if(stack.isEmpty() || stack.pop() != '[') return false; 12 }else if(ch == '}'){ 13 if(stack.isEmpty() || stack.pop() != '{') return false; 14 }else{ 15 return false; 16 } 17 } 18 return stack.isEmpty(); 19 }

浙公网安备 33010602011771号