原题链接:Leecode 20. 有效的括号
这道题就是一个简单的理解栈的题目。
以下两个代码思想是一样的,代码一长一点,代码二是精简过的。
代码一:
class Solution {
public:
bool isValid(string s) {
stack<char> st;
for(int i=0;i<s.size();i++)
{
if(s[i]=='(' ||s[i]=='{' || s[i]=='[' )
{
st.push(s[i]);
}
else
{
if(st.empty())
return false;
if(s[i]==')')
{
if(st.top()=='(')
st.pop();
else
return false;
}
if(s[i]=='}')
{
if(st.top()=='{')
st.pop();
else
return false;
}
if(s[i]==']')
{
if(st.top()=='[')
st.pop();
else
return false;
}
}
}
return st.empty();
}
};
代码二:
class Solution {
public:
bool isValid(string s) {
unordered_map<char,int> m=
{{'(',1},{'{',2},{'[',3},{')',4},{'}',5},{']',6}};
stack<char> st;
for(int i=0;i<s.size();i++)
{
int n=m[s[i]];
if(n>=1 && n<=3)
st.push(s[i]);
else
{
if(st.empty() || m[st.top()]!=n-3)
return false;
else
st.pop();
}
}
return st.empty();
}
};