代码随想录算法训练营第9天|20. 有效的括号、1047. 删除字符串中所有的相邻重复项、150. 逆波兰表达式求值
20. 有效的括号
提交代码()
class Solution {
public:
bool isValid(string s) {
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;
else if(st.empty())
return false;
else
st.pop();
}
return st.empty();
}
};
解答代码(方法)
class Solution {
public:
bool isValid(string s) {
int n = s.size();
if (n % 2 == 1) {
return false;
}
unordered_map<char, char> pairs = {
{
')', '('},
{
']', '['},
{
'}', '{'}
};
stack<char> stk;
for (char ch: s) {
if (pairs.count(ch)) {
if (stk.empty() || stk.top() != pairs[ch]) {
return false;
}
stk.pop();
}
else {
stk.push(ch);
}
}
return stk.empty();
}
};
1047. 删除字符串中所有的相邻重复项
提交代码(方法)
class Solution {
public:
string removeDuplicates(string s) {
stack<char> st;
for(int i = 0; i < s.size(); i++)
{
if(st.empty())
st.push(s[i]);
else if(s[i] == st.top())
st.pop();
else
st.push(s[i]);
}
string result;
while(!st.empty())
{
result.push_back(st.top());
st.pop();
}
reverse(result.begin(), result.end());
return result;
}
};
解答代码(方法)
class Solution {
public:
string removeDuplicates(string s) {
string stk;
for (char ch : s) {
if (!stk.empty() && stk.back() == ch) {
stk.pop_back();
} else {
stk.push_back(ch);
}
}
return stk;
}
};
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(num1 + num2);
else if(tokens[i] == "-")
st.push(num2 - num1);
else if(tokens[i] == "*")
st.push(num1 * num2);
else if(tokens[i] == "/")
st.push(num2 / num1);
}
else
st.push(stoll(tokens[i]));
}
return st.top();
}
};
解答代码(方法)
class Solution {
public:
int evalRPN(vector<string>& tokens) {
// 力扣修改了后台测试数据,需要用longlong
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;
}
};
总结
日期: 2023 年 3 月 26 日
学习时长: 0 h 30 m
难度: ★ \bigstar ★
累计完成题目数量: 30
距离目标还有数量: 270
小结:
- 第一题答案是用map存了一下,看起来简洁一些。
- 第二题感觉判断的有点复杂了,string本身就有类似入栈和出栈的接口
- stoll函数能将字符串转换为long long