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.
https://oj.leetcode.com/problems/valid-parentheses/
思路1:经典的栈匹配。一个栈,左符号入栈,右符号出栈。最后检查栈是否为空。
public class Solution {
public boolean isValid(String s) {
if (s == null || s.length() == 0)
return true;
Stack<Character> stack = new Stack<Character>();
int n = s.length();
for (int i = 0; i < n; i++) {
char ch = s.charAt(i);
if (ch == '(' || ch == '{' || ch == '[')
stack.push(ch);
else {
if (stack.isEmpty())
return false;
char out = stack.pop();
if (ch == ')' && out != '(' || ch == '}' && out != '{'
|| ch == ']' && out != '[')
return false;
}
}
if (!stack.isEmpty())
return false;
return true;
}
public static void main(String[] args) {
// true
System.out.println(new Solution().isValid("()"));
// true
System.out.println(new Solution().isValid("()[]{}"));
// false
System.out.println(new Solution().isValid("(]"));
// false
System.out.println(new Solution().isValid("([)]"));
}
}
第二遍记录:
算法不变,注意栈空判断。