匹配括号
LeetCode第20题(https://leetcode-cn.com/problems/valid-parentheses/)
方法一
分为三种情况①遍历了字符串,但是栈不为空,说明有相应的左括号,但是没有右括号;
②遍历过程中,发现栈中没有要匹配的字符;
③在遍历过程中栈已经为空,没有匹配的字符了
class Solution {
public:
bool isValid(string s) {
stack<int> st;
for(int i=0;i<s.size();i++)
{
if(s[i]=='(') st.push(')');
else if(s[i]=='{') st.push('}');
else if(s[i]=='[') st.push(']');
else if(st.empty()||st.top()!=s[i]) return false;
else st.pop();//st.top()与s[i]相等,栈弹出元素
}
return st.empty();
}
};
方法二
哈希表结合栈
当遇到匹配的最小括号对时,我们将这对括号从栈中删除(即出栈),如果最后栈为空,那么它是有效的括号,反之不是。
class Solution {
public:
bool isValid(string s) {
unordered_map<char,int> m{{'(',1},{'[',2},{'{',3},
{')',4},{']',5},{'}',6}};
stack<char> st;
bool istrue=true;
for(char c:s){
int flag=m[c];
if(flag>=1&&flag<=3) st.push(c);
else if(!st.empty()&&m[st.top()]==flag-3) st.pop();
else {istrue=false;break;}
}
if(!st.empty()) istrue=false;
return istrue;
}
};