https://leetcode.com/problems/valid-parentheses/
很简单的括号匹配判断,使用栈即可。
学过数据结构或者编译原理会很容易搞
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <stack>
using namespace std;
class Solution {
public:
bool isValid(string s) {
stack <char> sta;
for(int i=0;i<s.size();i++) {
//sta.push(s[i]);
if(s[i] == '(' ||
s[i] == '{' ||
s[i] == '[') {
sta.push(s[i]);
} else {
if(s[i] == ')' && sta.size()>0 && sta.top() == '(' ||
s[i]=='}' && sta.size()>0 && sta.top()=='{' ||
s[i]==']' && sta.size()>0 && sta.top()=='[') sta.pop();
else
return false;
}
}
if(sta.size() > 0)return false;
else return true;
}
};
int main() {
Solution s;
string str;
while(cin >> str) {
cout << s.isValid(str) << endl;
}
return 0;
}