20. 有效的括号
用栈,将左括号入栈 ,遍历的时候和栈顶元素比较。
第一种情况:已经遍历完了字符串,但是栈不为空,说明有相应的左括号没有右括号来匹配,所以return false
第二种情况:遍历字符串匹配的过程中,发现栈里没有要匹配的字符。所以return false
第三种情况:遍历字符串匹配的过程中,栈已经为空了,没有匹配的字符了,说明右括号没有找到对应的左括号return false
class Solution {
public:
bool isValid(string s) {
int size = s.size();
stack<char> st;
for(int i=0; i<size; i++){
if(s[i]=='(' || s[i]=='[' || s[i]=='{'){
st.push(s[i]);
}
else{
if(st.empty()) return false;
else if(s[i]==')' && st.top()=='('){
st.pop();
}
else if(s[i]==']' && st.top()=='['){
st.pop();
}
else if(s[i]=='}' && st.top()=='{'){
st.pop();
}
else return false;
}
}
return st.empty()? true : false;
}
};
1047. 删除字符串中的所有相邻重复项
用栈
class Solution {
public:
string removeDuplicates(string s) {
int size = s.size();
stack<char> st;
for(int i=0; i<size; i++){
if(st.empty()){
st.push(s[i]);
}
else{
if(st.top()==s[i]){
st.pop();
}
else{
st.push(s[i]);
}
}
}
string ans;
while(!st.empty()){
ans.push_back(st.top());
st.pop();
}
reverse(ans.begin(), ans.end());
return ans;
}
};
用字符串做栈
class Solution {
public:
string removeDuplicates(string s) {
string st;
for(auto str : s){
if(st.empty()||st.back()!=str){
st.push_back(str);
}
else{
st.pop_back();
}
}
return st;
}
};
150. 逆波兰表达式求值
遇到数字则入栈;遇到运算符则取出栈顶两个数字进行计算,并将结果压入栈中。
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> st;
int size = tokens.size();
for(int i=0; i<size; i++)
{
if(tokens[i]=="+" || tokens[i]=="-"
|| tokens[i]=="*" || tokens[i]=="/")
{
long num1 = st.top();
st.pop();
long num2 = st.top();
st.pop();
if(tokens[i]=="+"){st.push(num2 + num1);}
else if(tokens[i]=="-"){st.push(num2 - num1);}
else if(tokens[i]=="*"){st.push(num2 * num1);}
else{st.push(num2 / num1);}
}
else
{
st.push(atoi(tokens[i].c_str()));
}
}
int ans = st.top();
return ans;
}
};