一、题目打卡
1.1 有效的括号
题目链接:. - 力扣(LeetCode)
题目本身不难,主要理解栈在括号匹配时候的思路,而针对类似输入为 ']' 的情况,需要注意在所有的判断语句中都要加上判断是否为空的语句,否则可能会导致未定义的行为,最后为了防止输入的内容全部都是左括号,还需要改进最后返回的条件为 input.empty();
class Solution {
public:
bool isValid(string s) {
stack<char> input;
for(auto &it : s){
// cout << it << endl;
if(it == '[' || it == '{' || it == '('){
input.push(it);
}
else if(it == '}' && !input.empty()){
if(input.top() != '{') return false;
input.pop();
}
else if(it == ']' && !input.empty()){
if(input.top() != '[') return false;
input.pop();
}
else if(it == ')' && !input.empty()){
if(input.top() != '(') return false;
input.pop();
}else return false;
}
// return true;
return input.empty();
}
};
1.2 删除字符串中的所有相邻重复项
题目链接:. - 力扣(LeetCode)
做完这个题目,更能理解为什么匹配问题可以算做是栈处理的强项。
class Solution {
private:
stack<char> input;
public:
string removeDuplicates(string s) {
string res = "";
for(int i = 0 ; i < s.size(); i++){
if(res.empty() || s[i] != input.top()){
res.push_back(s[i]);
input.push(s[i]);
}
else if(!input.empty() && s[i] == input.top()){
input.pop();
res.pop_back();
}
}
return res;
}
};
阅读了答案,发现其实题目可以进一步优化,不需要申请那么多内存空间,可以直接利用string 所包含的 back() 方法访问最后一个元素来进行判断:
class Solution {
public:
string removeDuplicates(string s) {
string res = "";
for(int i = 0 ; i < s.size(); i++){
if(res.empty() || res.back() != s[i]){
res.push_back(s[i]);
}
else if(s[i] == res.back()){
res.pop_back();
}
}
return res;
}
};
1.3 逆波兰表达式求值
题目链接:. - 力扣(LeetCode)
class Solution {
private:
stack<int> input;
public:
int evalRPN(vector<string>& tokens) {
for(auto & i : tokens){
if(i.size() == 1 && (i[0] == '+' || i[0] == '-' || i[0] == '*' || i[0] =='/')){
char it = i[0];
int tmp1 = input.top();
input.pop();
int tmp2 = input.top();
input.pop();
if(it == '+') input.push(tmp1 + tmp2);
else if(it == '-') input.push(tmp2 - tmp1);
else if(it == '*') input.push(tmp1 * tmp2);
else input.push(tmp2 / tmp1);
}else{
input.push(stoi(i));
}
}
return input.top();
}
};
写的过程有一点点不顺利,但是思路是没问题的,踩的坑:
这个输入的部分,每一个索引对应的是一个字符串,这一点很重要,所以对于数字和符号的处理需要注意,另外 '-' 这个符号还需要注意,因为这个输入里面存在负数,所以符号的判断最好是在前面加上一个判断 size 等不等于 1,最后就是在进行除法和减法的时候,需要注意临时变量的顺序问题。
看答案在处理的时候使用的库函数是 stoll ,前面的变量声明也都用的是long long ,也许这个是为了防止越界?但是我看最后我运行通过了,也就是说案例里面应该不存在 int 越界的情况,所以我没有进一步修改,思路和答案的是一样的。