#include<stack>
#include<string>
#include<iostream>
using namespace std;
class Solution {
public:
bool isValid(string s) {
int length = s.size();
int i = 1;
stack<char> temp;
if (length == 0){
return false;
}
temp.push(s[0]);
while (i< length){
//cout << s[i] << endl;
if (s[i] == '(' || s[i] == '[' || s[i] == '{'){
//cout << "push" << s[i] << endl;
temp.push(s[i]);
}
else{
//这个上面的else很重要,因为当s[i]不是左括号时,此时栈已经空了,如果出现右边符号,就是没有匹配的左值符号,没有检测下去的必要。
if (temp.empty()){
return false;
}
else if (s[i] == ')'){
if (temp.top() == '('){
temp.pop();
}
else{
return false;
}
}
else if (s[i] == '}'){
if (temp.top() != '{'){
return false;
}
else{
temp.pop();
}
}
else if (s[i] == ']'){
if (temp.top() != '['){
return false;
}
else{
temp.pop();
}
}
}
i++;
}
if (!temp.empty()){
return false;
}
else{
return true;
}
}
};
int main(){
string s = "[])";
Solution obj;
bool res;
res = obj.isValid(s);
if (res == true){
cout << "true " << endl;
}
else{
cout << "false " << endl;;
}
while (1);
return 1;
}
Valid Parentheses
最新推荐文章于 2021-03-21 16:39:09 发布