标签:
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为空,则所有括号匹配。
1 public class Solution { 2 /** 3 * @param s A string 4 * @return whether the string is a valid parentheses 5 */ 6 public boolean isValidParentheses(String s) { 7 if (s == null || s.length() % 2 == 1) return false; 8 Stack<Character> stack = new Stack<Character>(); 9 10 for (int i = 0; i < s.length(); i++) { 11 if (stack.size() == 0) { 12 stack.push(s.charAt(i)); 13 } else { 14 char c1 = stack.peek(); 15 char c2 = s.charAt(i); 16 if (c1 == ‘(‘ && c2 == ‘)‘ || c1 == ‘[‘ && c2 == ‘]‘ || c1 == ‘{‘ && c2 == ‘}‘) { 17 stack.pop(); 18 } else { 19 stack.push(s.charAt(i)); 20 } 21 } 22 } 23 return stack.isEmpty(); 24 } 25 }
标签:
原文地址:http://www.cnblogs.com/beiyeqingteng/p/5666139.html