版权声明: https://blog.csdn.net/ysq96/article/details/89710060
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
题意:题目要求给一串可能包含大、中、小括号的字符串,让你判断这个是否正确。括号序列判定就是利用栈啦。
C++:注意当时右括号时要先判断下栈是否为空,若为空则返回false,若不为再进行出栈的操作
class Solution {
public:
bool isValid(string s) {
stack<char> c;
if(s.length()==0) return true;
for(int i=0;i<s.length();i++){
if(s[i]=='('||s[i]=='{'||s[i]=='['){
c.push(s[i]);
}else{
if(c.empty())return false;
char temp=c.top();
c.pop();
if(temp=='('&&s[i]!=')')return false;
if(temp=='{'&&s[i]!='}')return false;
if(temp=='['&&s[i]!=']')return false;
}
}
if(!c.empty())return false;
return true;
}
};
Python3:最简单的办法其实就是每次将字符串中的正确括号去掉
class Solution:
def isValid(self, s: str) -> bool:
while '{}' in s or '[]' in s or '()' in s:
s=s.replace('{}','')
s=s.replace('[]','')
s=s.replace('()','')
return s==''