20. 有效的括号
class Solution {
public:
bool isValid(string s) {
if (s.size()%2!=0) return false;
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; //说明此时s中有无法对应的右括号
else st.pop(); //说明遇到了右括号,出栈,并且由于上一句代码已经保证了s[i]与栈顶元素相同
}
return st.empty(); //如果遍历完正好栈清空则返回true,反之false
}
};
注意多余右括号的处理方法,如果s还没遍历完,但是st遍历完了,这就说明st中有多余的右括号。
返回遍历完s之后返回st.empty()如果st不为空,说明有多余的左括号;为空说明正好完全匹配。
1047. 删除字符串中的所有相邻重复项
class Solution {
public:
string removeDuplicates(string s) {
string result; //将这个字符串看做一个栈,对他的操作与栈类似
for (char c : s){
if (result.empty() || c!=result.back()){
result.push_back(c);
}
else{
result.pop_back();
}
}
return result;
}
};
150. 逆波兰表达式求值
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<long long> rpn;
for (int i=0; i<tokens.size(); i++){
if (tokens[i]=="+"){
long long stTop1 = rpn.top();
rpn.pop();
long long stTop2 = rpn.top();
rpn.pop();
rpn.push(stTop2+stTop1);
}
else if (tokens[i]=="-"){
long long stTop1 = rpn.top();
rpn.pop();
long long stTop2 = rpn.top();
rpn.pop();
rpn.push(stTop2-stTop1);
}
else if (tokens[i]=="*"){
long long stTop1 = rpn.top();
rpn.pop();
long long stTop2 = rpn.top();
rpn.pop();
rpn.push(stTop2*stTop1);
}
else if (tokens[i]=="/"){
long long stTop1 = rpn.top();
rpn.pop();
long long stTop2 = rpn.top();
rpn.pop();
rpn.push(stTop2/stTop1);
}
else{
rpn.push(stoll(tokens[i]));
}
}
return rpn.top();
}
};
注意点1:对比±*/这些const char时,需要给他们加上双引号。
2:进行计算时,是后出栈的元素在前面进行计算,因为先进后出。