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() || st.top() != s[i]) {
return false;
} else {
st.pop();
}
}
return st.empty();
}
};
题目链接/文章讲解/视频讲解:https://programmercarl.com/0020.%E6%9C%89%E6%95%88%E7%9A%84%E6%8B%AC%E5%8F%B7.html
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 if (st.top() == s[i]) {
// 如果相等就弹出
st.pop();
}
}
string result;
// 依次取出栈中的元素
while (!st.empty()) {
result += st.top();
st.pop();
}
// 还要再取反一下
reverse(result.begin(), result.end());
return result;
}
};
150. 逆波兰表达式求值
这里if判断是数字不好判断,因为操作符的情况好写,所以else是数字的情况。
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 a = st.top();
st.pop();
long long b = st.top();
st.pop();
if (tokens[i] == "+") st.push(b + a);
else if (tokens[i] == "-") st.push(b - a);
else if (tokens[i] == "*") st.push(b * a);
else if (tokens[i] == "/") st.push(b / a);
} else {
st.push(stoll(tokens[i]));
}
}
return st.top();
}
};
题目链接/文章讲解/视频讲解:https://programmercarl.com/0150.%E9%80%86%E6%B3%A2%E5%85%B0%E8%A1%A8%E8%BE%BE%E5%BC%8F%E6%B1%82%E5%80%BC.html