20. 有效的括号栈的应用,在写时要考虑三种情况:1.左括号冗余 ,判断条件为最后栈不为空;2.右括号冗余,判断条件为循环未结束而栈已空;3.括号匹配错位,判断条件为栈顶元素与当前右括号不一致;
class Solution {
public:
bool isValid(string s) {
if(s.size()%2!=0){
return false;
}
stack<char> ch;
for(int i=0;i<s.size();i++){
if(s[i]=='(' ){
ch.push(')');
}
else if(s[i]=='{'){
ch.push('}');
}
else if(s[i]=='['){
ch.push(']');
}
//这里包括了两种情况:1.右括号多余 2.括号匹配错误
else if(ch.empty()||ch.top()!=s[i]){
return false;
}
else ch.pop();
}
//包括另一种情况:即左括号多余(如果最后的栈不是空 说明没用多余左括号,返回true)
return ch.empty();
}
};
1047. 删除字符串中的所有相邻重复项同样是栈的应用
class Solution {
public:
string removeDuplicates(string s) {
stack<char> st;
for(int i=0;i<s.size();i++){
if(st.empty()||st.top()!=s[i]){
st.push(s[i]);
}
else {
st.pop();
}
}
string result = "";
while(!st.empty()){
result+=st.top();
st.pop();
}
//最后需要反转一下字符串
reverse(result.begin(),result.end());
return result;
}
};
150. 逆波兰表达式求值学数据结构的时候就会这个算法了
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<long long> st;
for(int i=0;i<tokens.size();i++){
if(tokens[i]=="+"||tokens[i]=="-"||tokens[i]=="*"||tokens[i]=="/"){
long long num1 = st.top();
st.pop();
long long num2 = st.top();
st.pop();
if(tokens[i]=="+") st.push(num2+num1);
if(tokens[i]=="-") st.push(num2-num1);
if(tokens[i]=="*") st.push(num2*num1);
if(tokens[i]=="/") st.push(num2/num1);
}
else{
//std::stoll() 是 C++ 标准库中的一个函数
//用于将字符串转换为长整数类型 (long long)
st.push(stoll(tokens[i]));
}
}
int result = st.top();
return result;
}
};