文章目录
1. Leetcode 20 有效的括号
(1)解析
(2)思路
先确定3种情况:
第一种情况:已经遍历完了字符串,但是栈不为空,说明有相应的左括号没有右括号来匹配,所以return false
第二种情况:遍历字符串匹配的过程中,发现栈里没有要匹配的字符。所以return false
第三种情况:遍历字符串匹配的过程中,栈已经为空了,没有匹配的字符了,说明右括号没有找到对应的左括号return false
(3)代码
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] == '(' || s[i] == '{' || s[i] == '[')
st.push(s[i]);
else if(s[i] == ')' || s[i] == '}' || s[i] == ']')
{
if(st.empty())
return false;
char ch = st.top();
if(s[i] == ')' && ch == '(')
st.pop();
else if(s[i] == ']' && ch == '[')
st.pop();
else if(s[i] == '}' && ch == '{')
st.pop();
else
return false;
}
}
if(!st.empty())
return false;
else
return true;
}
};
(4)总结
参考文章的思路值得借鉴,在匹配左括号的时候,右括号先入栈,就只需要比较当前元素和栈顶相不相等就可以了,比左括号先入栈代码实现要简单的多了;if(s.size() % 2 != 0)可以预先去除无意义的操作。
2. Leetcode 1047 删除字符串中的所有相邻重复项
(1)解析
(2)思路
a.栈的思路
b.st为空的判断
b.string出栈取反操作
(3)代码
class Solution {
public:
string removeDuplicates(string s) {
if(s.size() == 1)
return s;
stack<char> st;
st.push(s[0]);
for(int i = 1; i < s.size(); ++i)
{
if(!st.empty() && s[i] == st.top())
st.pop();
else
st.push(s[i]);
}
string res = "";
while(!st.empty())
{
res += st.top();
st.pop();
}
reverse(res.begin(), res.end());
return res;
}
};
(4)总结
无
3. Leetcode 150 逆波兰表达式求值
(1)解析
(2)思路
遇到操作符就出栈
(3)代码
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] != "/")
st.push(stoll(tokens[i]));
else
{
long long num2 = st.top();
st.pop();
int num1 = st.top();
st.pop();
int res;
if(tokens[i] == "+")
res = num1 + num2;
if(tokens[i] == "-")
res = num1 - num2;
if(tokens[i] == "*")
res = num1 * num2;
if(tokens[i] == "/")
res = num1 / num2;
st.push(res);
}
}
return st.top();
}
};
(4)总结
a.stoll函数的实验,string转long long