代码随想录算法训练营第十一天 20.有效的括号 | 1047. 删除字符串中的所有相邻重复项 | 150. 逆波兰表达式求值
栈应用 lc20 有效的括号
本题考验的是对栈操作的理解,关键在于梳理逻辑,写出判断条件。在写代码之前想清楚可能存在的不匹配的情况(左括号多了,右括号不匹配最近的左括号,右括号多了)
class Solution {
public:
bool isValid(string s) {
stack<char> expect;
for (char c : s){
//出现左括号的情况
if(c=='(') expect.push(')');
else if(c=='[') expect.push(']');
else if(c=='{') expect.push('}');
//出现右括号的情况
//栈已经为空,或没有与最近的左括号匹配 返回false
else if(expect.empty() || expect.top() != c) return false;
//右括号匹配,弹出
else expect.pop();
}
//检查栈是否为空,有可能有多余的左括号
return expect.empty();
}
};
栈应用 lc1047 删除字符串中的所有相邻重复项
本题可以使用栈来解决,在栈为空或者栈顶元素与字符串遍历元素不相同时进行压栈,相等时出栈。直接使用string来搭建栈的结构可以节省掉将栈转为string的工作。
使用string搭建栈
class Solution {
public:
string removeDuplicates(string s) {
string result;
for(char c : s ){
if(result.empty() || result.back() != c){
result.push_back(c);
}
else{
result.pop_back();
}
}
return result;
}
};
代码随想录 直接使用stack
class Solution {
public:
string removeDuplicates(string S) {
stack<char> st;
for (char s : S) {
if (st.empty() || s != st.top()) {
st.push(s);
} else {
st.pop(); // s 与 st.top()相等的情况
}
}
string result = "";
while (!st.empty()) { // 将栈中元素放到result字符串汇总
result += st.top();
st.pop();
}
reverse (result.begin(), result.end()); // 此时字符串需要反转一下
return result;
}
};
栈应用 lc150 逆波兰表达式求值
本题重要概念在于逆波兰表达式,或后缀表达式。后缀表达式对计算机十分友好,让计算机立刻明白了计算的顺序。使用栈来进行对后缀表达式进行求值分为以下步骤:
- 建立空栈来存储数据
- 遍历输入的后缀表达式
- 遇到数字时将其压入栈
- 遇到符号时,弹出两个数字并使用该符号进行计算,将得到的值压入栈
后缀表达式 和 逆序遍历二叉树也有些关系。
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> st;
for (string s : tokens){
if (s == "+" || s == "-" || s == "*" || s == "/"){
int n2 = st.top();
st.pop();
int n1 = st.top();
st.pop();
if(s == "+") st.push(n1 + n2);
else if(s == "-") st.push(n1 - n2);
else if(s == "*") st.push(n1 * n2);
else if(s == "/") st.push(n1 / n2);
}
else{
st.push(stol(s));
}
}
return st.top();
}
};
本文作者:冰镇杨梅
本文链接:https://www.cnblogs.com/frozenwaxberry/p/17067502.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
分类:
标签:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步