思路:
用栈来做括号匹配,左括号入栈,右括号跟栈内匹配,匹配继续 ,不匹配则return false,直至所有符号循环结束,若结束后栈空则匹配,否则不匹配。
# include<iostream>
# include<vector>
# include<string>
# include<algorithm>
# include<math.h>
# include<climits>
# include<stack>
using namespace std;
bool check(char c1, char c2) {
if (c1 == '(' && c2 == ')')
return true;
if (c1 == '{' && c2 == '}')
return true;
if (c1 == '[' && c2 == ']')
return true;
return false;
}
bool isValid(string s) {
stack<char>p;
for (int i = 0; i < s.size(); i++) {
if(s.at(i)=='('|| s.at(i) == '{'|| s.at(i) == '[')
p.push(s.at(i));//将每一个东西都入栈
else {
if (!p.empty()) {
char c = p.top();//拿到栈顶元素
if (check(c, s.at(i)))p.pop();
else
return false;
}
else return false;
}
}
if (p.empty())return true;
return false;
}
int main(void) {
cout << isValid("]");
return 0;
}