Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:
Input: "()" Output: true
Example 2:
Input: "()[]{}" Output: true
Example 3:
Input: "(]" Output: false
Example 4:
Input: "([)]" Output: false
Example 5:
Input: "{[]}" Output: true
题意:
给定一个括号序列,判断其是否合法。
扫描二维码关注公众号,回复:
1400853 查看本文章
思路:
指针i来扫给定字符串
对于字符串的每个char,若是左括号,入栈
若栈不为空&&栈顶元素与对应位置的右括号匹配,出栈
代码:
1 public class ValidParentheses { 2 public boolean isValid(String s) { 3 final String left = "([{"; 4 final String right = ")]}"; 5 Stack<Character> stack = new Stack<>(); 6 7 for (int i = 0; i < s.length(); ++i) { 8 char c = s.charAt(i); 9 if (left.indexOf(c) != -1) { 10 stack.push(c); 11 } else { 12 if (!stack.isEmpty() && 13 stack.peek() == left.charAt(right.indexOf(c))) 14 stack.pop(); 15 else 16 return false; 17 } 18 } 19 return stack.empty(); 20 } 21 }