目录
LeeCode 20.有效的括号
LeeCode 1047. 删除字符串中的所有相邻重复项
LeeCode 150. 逆波兰表达式求值
LeeCode 20.有效的括号
思路:利用栈先进后出的特性,将左括号对应的右括号存在栈中,当遇到右括号时入栈,比较当前元素与栈顶元素是否一致,即可判断括号是否匹配。
class Solution {
public:
bool isValid(string s) {
//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();
}
};
LeeCode 1047. 删除字符串中的所有相邻重复项
思路: 类比上方匹配括号问题,此题目为匹配字母,同样用栈解决。
class Solution {
public:
string removeDuplicates(string s) {
stack<char> st;
for (char s1 : s){
if (st.empty() || s1 != st.top()) {
st.push(s1);
}
else {
st.pop();
}
}
string result = "";
while (!st.empty()) {
result += st.pop();
st.pop();
}
reverse (result.begin(), result.end());
return result;
}
};
LeeCode 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 {
st.push(stoll(tokens[i]));
}
}
int result = st.top();
st.pop();
return result;
}
};