LeetCode 20. Valid Parentheses
考点 | 难度 |
---|---|
String | Easy |
题目
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.
思路
用stack,如果是前半个括号就push到stack里,后半个括号检查和pop出来的括号是不是匹配,如果不匹配返回false
。最后检查stack里有没有多余的括号,有的话返回false
。
答案
class Solution {
public boolean isValid(String s) {
Stack<Character> st = new Stack<>();
for(int i = 0; i < s.length(); i++) {
char a = s.charAt(i);
if(a == '(' || a == '[' || a == '{') {
st.push(a);
}
else if(st.empty()) {
return false;
}
else if(a == ')' && st.pop() != '(') {
return false;
}
else if(a == ']' && st.pop() != '[') {
return false;
}
else if(a == '}' && st.pop() != '{') {
return false;
}
}
return st.empty();
}
}