Leetcode 20. Valid Parentheses
Given a string s
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.
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
Example 4:
Input: s = "([)]"
Output: false
Example 5:
Input: s = "{[]}"
Output: true
Constraints:
1 <= s.length <= 104
s
consists of parentheses only'()[]{}'
.
Solution(java):
class Solution {
public boolean isValid(String s) {
char[] symbol = {'(' , ')' , '{' , '}' , '[' , ']' };
int len = s.length();
if(len%2 != 0 ) return false;
Stack<Character> parentheses= new Stack<Character>();
for(int i = 0 ; i<s.length(); i++){
if (s.charAt(i) == symbol[0]) parentheses.push(s.charAt(i));
if (s.charAt(i) == symbol[2]) parentheses.push(s.charAt(i));
if (s.charAt(i) == symbol[4]) parentheses.push(s.charAt(i));
if (parentheses.empty()) return false;
else if (s.charAt(i) == symbol[1] ) {
if (parentheses.peek() !=symbol[0] ) return false;
else parentheses.pop();
}
else if (s.charAt(i) == symbol[3]) {
if (parentheses.peek() !=symbol[2] ) return false;
else parentheses.pop();
}
else if (s.charAt(i) == symbol[5]) {
if (parentheses.peek() !=symbol[4] ) return false;
else parentheses.pop();
}
}
return parentheses.empty();
}
}
使用栈来解决该问题:
栈的特点: 后进先出
如遇到左半边括号:放入栈中。
如遇到右半边括号:若此时栈为空(parentheses.empty() ),则return false.
否则,判断栈顶元素(parentheses.peek())与当前括号是否匹配,若匹配,则继续循环。若不匹配,则return false.
最后判断栈是否为空,若栈为空,则该问题为true。
参考资料: