2023.6.19
栈的经典应用,括号匹配 问题。 思路是构建一个临时栈,然后遍历字符串,如果是( { [ 就放入栈,如果不是就判断一下栈顶是否和{ ( [ 匹配,如果不匹配就返回false。 遍历完后,如果栈是空的则返回true。 直接看代码:
class Solution {
public:
bool isValid(string s) {
stack<char> sta;
//字符串的字符个数是奇数,直接返回false。
if(s.size()%2 != 0) return false;
for(int i=0; i<s.size(); i++)
{
if(s[i] == '(' || s[i] == '[' || s[i] == '{') sta.push(s[i]);
else
{
if(sta.empty() || s[i]==')'&&sta.top()!='(') return false;
else if(sta.empty() || s[i]==']'&&sta.top()!='[') return false;
else if(sta.empty() || s[i]=='}'&&sta.top()!='{') return false;
else sta.pop();
}
}
return sta.empty();
}
};
2023.9.23
时隔三个月,二刷。看到括号匹配就想到要用栈,逻辑就类似消消乐,最后栈的元素要是都消完了就返回true。
代码风格稍微有些变化:
class Solution {
public:
bool isValid(string s) {
stack<char> stk;
int i = 0;
while(i<s.size())
{
if(stk.empty()) stk.push(s[i]);
else
{
if(stk.top() == '(')
{
if(s[i] == ')') stk.pop();
else stk.push(s[i]);
}
else if(stk.top() == '[')
{
if(s[i] == ']') stk.pop();
else stk.push(s[i]);
}
else if(stk.top() == '{')
{
if(s[i] == '}') stk.pop();
else stk.push(s[i]);
}
}
i++;
}
if(stk.empty()) return true;
return false;
}
};