https://leetcode-cn.com/problems/valid-parentheses/
给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例:
输入: “()”
输出: true
示例 2:
输入: “()[]{}”
输出: true
示例 3:
输入: “(]”
输出: false
示例 4:
输入: “([)]”
输出: false
输入: “{[]}”
输出: true
解法1
60 ms 12 MB
评论区网友给的解法,python 版本。
class Solution:
def isValid(self, s):
while '{}' in s or '()' in s or '[]' in s:
s = s.replace('{}', '')
s = s.replace('[]', '')
s = s.replace('()', '')
return s == ''
解法2
4ms, 6.4mb
使用 stack,当遇到一个左括号时候,就往栈中 push 一个对应的右括号,如果碰到了右括号,栈顶元素 != 当前右括号,或者当前栈为空(没有匹配)就 return false。
class Solution {
public:
bool isValid(string s) {
if (s == "") {
return true;
}
stack<char> st;
for (int i = 0; i < s.size(); ++i) {
switch(s[i]) {
case '(':
st.push(')');
break;
case '{':
st.push('}');
break;
case '[':
st.push(']');
break;
default:
if (st.empty() || s[i] != st.top()) {
return false;
} else {
st.pop();
}
}
}
if (st.empty()) {
return true;
} else {
return false;
}
}
};
EOF