题目描述
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
如果括号以正确的顺序闭合,则称字符串是有效的。例如,"()","{[]}"和 "()[]{}" 是有效的,但是 "(]" 和 "([)]" 不是。
解题思路分析
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
for (char c : s.toCharArray()) {
if (c == '(')
stack.push(')');
else if (c == '{')
stack.push('}');
else if (c == '[')
stack.push(']');
else if (stack.isEmpty() || stack.pop() != c) //注意这个地方
return false;
}
return stack.isEmpty();
}
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
// Iterate through string until empty
for(int i = 0; i<s.length(); i++) {
// Push any open parentheses onto stack
if(s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{')
stack.push(s.charAt(i));
// Check stack for corresponding closing parentheses, false if not valid
else if(s.charAt(i) == ')' && !stack.empty() && stack.peek() == '(')
stack.pop();
else if(s.charAt(i) == ']' && !stack.empty() && stack.peek() == '[')
stack.pop();
else if(s.charAt(i) == '}' && !stack.empty() && stack.peek() == '{')
stack.pop();
else
return false;
}
// return true if no open parentheses left in stack
return stack.empty();
}