给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解决办法:
方法一:
C++
class Solution{
public:
bool IsValid(string s){
stack<char> stack;
for(const auto& achar : s ){
if(stack.size() == 0){
stack.push(achar);
}
else if(IsSym(stack.top(), achar)){
stack.pop();
}
else{
stack.push();
}
}
return stack.size() == o;
private: bool IsSym(char b1, char b2){
return (b1=='[' && b2==']') || (b1=='{' && b2=='}') || (b1=='(' && b2==')');
}
python 实现
这简直是大神的操作
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
while '()' in s or '[]' in s or '{}' in s:
s = s.replace('()', '')
s = s.replace('[]', '')
s = s.replace('{}', '')
return s == ''