栈的一些典型应用:
class Solution {
public:
bool isValid(string s) {
stack<char> 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() || s[i] != st.top()) return false;
else st.pop();
}
return st.empty();
}
};
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<long long> st;
long long num1 = 0;
long long num2 = 0;
for(int i = 0; i < tokens.size(); i++)
{
if(tokens[i] != "+" && tokens[i] != "-" && tokens[i] != "*" && tokens[i] != "/") st.push(stoll(tokens[i]));
else
{
num1 = st.top();
st.pop();
num2 = st.top();
st.pop();
if(tokens[i] == "+") st.push(num1 + num2);
else if(tokens[i] == "-") st.push(num2 - num1);
else if(tokens[i] == "*") st.push(num1 * num2);
else st.push(num2 / num1);
}
}
return st.top();
}
};
class Solution {
public:
string removeDuplicates(string s) {
string sNew;
for(int i = 0; i < s.size(); i++)
{
if(sNew.empty() || s[i] != sNew.back()) sNew.push_back(s[i]);
else sNew.pop_back();
}
return sNew;
}
};