题目链接:https://leetcode.com/problems/valid-parentheses/description/
题目大意:简单的括号 匹配问题。
法一:栈,代码如下(耗时 9ms):
1 public boolean isValid(String s) { 2 char[] str = s.toCharArray(); 3 Stack<Character> stack = new Stack<Character>(); 4 for(int i = 0; i < str.length; i++) { 5 if(str[i] == '(' || str[i] == '[' || str[i] == '{') { 6 stack.push(str[i]); 7 } 8 else if(str[i] == ')') { 9 if(!stack.isEmpty() && stack.pop() == '(') { 10 continue; 11 } 12 else { 13 return false; 14 } 15 } 16 else if(str[i] == ']') { 17 if(!stack.isEmpty() && stack.pop() == '[') { 18 continue; 19 } 20 else { 21 return false; 22 } 23 } 24 else if(str[i] == '}') { 25 if(!stack.isEmpty() && stack.pop() == '{') { 26 continue; 27 } 28 else { 29 return false; 30 } 31 } 32 } 33 if(!stack.isEmpty()) { 34 return false; 35 } 36 return true; 37 }
法二(借鉴):思想略不同,更简易代码,https://leetcode.com/problems/valid-parentheses/discuss/