LeetCode 20.有效的括号
题目链接:20.有效的括号
踩坑:要记得往栈里压的是左括号还是右括号
思路:核心是最后出现的左括号一定是最先被消掉的
- 我自己的思路:遇到左括号就压入栈,遇到右括号则弹出栈顶元素对比,若不是对应左括号则false。最后栈不为空也false
- 卡哥的思路:遇到左括号就压入相应的右括号,遇到右括号则弹出栈顶元素对比,若不相等则false,最后栈不为空也false
代码:
// 我自己的思路
class Solution {
public:
bool isValid(string s) {
stack<char> st;
for(int i = 0; i < s.length(); i++)
{
if(s[i] == '(' || s[i] == '[' || s[i] == '{') st.push(s[i]);
else
{
if(!st.empty())
{
char t = st.top();
st.pop();
if(s[i] == ')' && t != '(') return false;
else if(s[i] == ']' && t != '[') return false;
else if(s[i] == '}' && t != '{') return false;
}
else return false;
}
}
if(st.empty()) return true;
else return false;
}
};
LeetCode 1047.删除字符串中的所有相邻重复项
题目链接:1047.删除字符串中的所有相邻重复项
踩坑:不用去想有3个重复的怎么办,题目已经说明是相邻的两个。另外,栈转化为字符串可以用“+”重载。
思路:遍历字符串,与栈顶元素比较,若不同则入栈,若相同则出栈。
思路:
class Solution {
public:
string removeDuplicates(string s) {
stack<int> st;
string result = "";
for(int i = 0; i < s.length(); i++)
{
if(!st.empty() && st.top() == s[i]) st.pop();
else st.push(s[i]);
}
while(!st.empty())
{
result += st.top();
st.pop();
}
reverse(result.begin(), result.end());
return result;
}
};
LeetCode 150.逆波兰表达式求值
题目链接:150.逆波兰表达式求值
踩坑:一时没有想起来运算完的结果要再次压入栈中
思路:遇到运算符就从栈里弹出两个元素做运算,结果在压会栈里。注意做减法和除法时后弹出的元素做被减/除数。
代码:
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> st;
for(int i = 0; i < tokens.size(); i++)
{
if(tokens[i] == "+")
{
int a, b;
a = st.top();
st.pop();
b = st.top();
st.pop();
st.push(a+b);
}
else if(tokens[i] == "-")
{
int a, b;
a = st.top();
st.pop();
b = st.top();
st.pop();
st.push(b-a);
}
else if(tokens[i] == "*")
{
int a, b;
a = st.top();
st.pop();
b = st.top();
st.pop();
st.push(b*a);
}
else if(tokens[i] == "/")
{
int a, b;
a = st.top();
st.pop();
b = st.top();
st.pop();
st.push(b/a);
}
else st.push(stoi(tokens[i]));
}
return st.top();
}
};