20. Valid Parentheses
Difficulty: Easy
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
思路
简单的水题,一开始将判断语句逻辑写错了;
if (i == 0 || sta.empty() || sta.top() != '(')
写成if (sta.top() != '(' || sta.empty() || i == 0 )
原因:当stack
为空时,调用了sta.top()
导致的。先判断i==0即可解决。
Solution
Language: C++
class Solution {
public:
bool isValid(string s) {
stack<char> sta;
for (int i = 0; i < s.length(); i++){
if (s[i] == '(' || s[i] == '[' || s[i] == '{'){
sta.push(s[i]);
}
else if (s[i] == ')'){
if (i == 0 || sta.empty() || sta.top() != '('){
return false;
}
sta.pop();
}
else if (s[i] == '}'){
if (i == 0 || sta.empty() || sta.top() != '{'){
return false;
}
sta.pop();
}
else if (s[i] == ']'){
if (i == 0 || sta.empty() || sta.top() != '['){
return false;
}
sta.pop();
}
}
return sta.empty();
}
};