#include<iostream>
#include<stack>
#include<string>
using namespace std;
class Solution {
public:
bool isValid(string s) {
stack<char> sta;
if(s[0] == '(' || s[0] == '[' || s[0] == '{'){
sta.push(s[0]);
}else{
return false;
}
int len = s.length();
for(int i = 1; i < len ; i++){
if (s[i] == '(' || s[i] == '[' || s[i] == '{'){
sta.push(s[i]);
}
else if(sta.empty() || sta[i] == ']' && sta.top() != '[' ||sta[i] == ')' && sta.top() != '(' ||sta[i] == '}' && sta.top() != '{') {
return false;
}
else{
sta.pop();
}
}
if (sta.size() == 0){
return true;
}
else{
return false;
}
}
};
int main(){
Solution so;
string str = "()";
cout << "the res is: " << so.isValid(str) << endl;
}
leetcode 20 Valid Parentheses
最新推荐文章于 2019-10-10 10:29:04 发布