
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/shiliang97/article/details/101993070
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Note that an empty string is also considered valid.
Example 1:
Input: "()"
Output: trueExample 2:
Input: "()[]{}"
Output: trueExample 3:
Input: "(]"
Output: falseExample 4:
Input: "([)]"
Output: falseExample 5:
Input: "{[]}"
Output: trueclass Solution {
public:
bool isValid(string s) {
stack<int> t;
for(int i=0;i<s.length();i++)
{
if(s[i]=='('||s[i]=='['||s[i]=='{'){
t.push(s[i]);
}else if(s[i]==')'){
if(i==0||t.empty()||t.top()!='('){
return false;
}
t.pop();
}else if(s[i]=='}'){
if(i==0||t.empty()||t.top()!='{'){
return false;
}
t.pop();
}else if(s[i]==']'){
if(i==0||t.empty()||t.top()!='['){
return false;
}
t.pop();
}
}
return t.empty();
}
};