#include <iostream>
#include <algorithm>
#include <vector>
#include <stack>
using namespace std;
class Solution {
//核心思想: 判断字符如果是[ ( { 中的一种, 就放入到栈中(放到栈中的是左括号的下标,这样与他对应的是右括号的下标
//(左括号下标等于右括号下标-3)
//如果压入栈中的字符与已经放在栈顶的字符对应,那么就出栈,不对应的话就说明错误,返回就行.
public:
bool isValid(string s) {
if (s.size() == 0)
return false;
stack<char> stk;
string match("({[)}]");
for (int i = 0; i < s.size(); i++){
if (match.find(s[i]) <= 2){
//由放的是位置下标 总是犯错
stk.push(match.find(s[i]));
}
else{
if (!stk.empty()){
int temp = stk.top();
if (temp == match.find(s[i])-3){
stk.pop();
}
else
return false;
}
else
return false;
}
}
if (stk.empty()) return true;
else return false;
}
};
int main()
{
Solution s = Solution();
string str("[(){}]");
bool flag = s.isValid(str);
cout << flag << endl;
system("pause");
return 0;
}
有效的符号匹配
最新推荐文章于 2021-08-13 19:20:53 发布