字符串相邻项匹配问题,一般就是考虑用栈的方法来做,其实就是一个简单的栈的应用,这个回溯法那个可能的扩号组合方案的题目还不一样,不需要去把所有可能都输出出来(当然也没那么多可能咯)
class Solution {
public:
bool isValid(string s) {
stack<char> matchStack;
unordered_map<char,char> match_map;
match_map.insert(pair<char,char>('(',')'));
match_map.insert(pair<char,char>('[',']'));
match_map.insert(pair<char,char>('{','}'));
for(auto i : s){
if(!matchStack.empty() && match_map.find(matchStack.top()) != match_map.end() && match_map.find(matchStack.top())->second == i){
matchStack.pop();
}else{
matchStack.push(i);
}
}
if(matchStack.empty()){
return true;
}
return false;
}
};
左右括号的匹配操作使用了哈希表的方法,总体上这道题还是简单的,就是写的时候要注意空栈,空哈希表的情况,避免出错
同样的,这是一道字符串邻项匹配的问题,和有效的括号这道题很像,用一下栈来做
class Solution {
public:
string removeDuplicates(string s) {
stack<char> matchStack;
for(auto i : s){
if(!matchStack.empty() && matchStack.top() == i){
matchStack.pop();
}else{
matchStack.push(i);
}
}
string res = "";
while(!matchStack.empty()){
res.push_back(matchStack.top());
matchStack.pop();
}
reverse(res.begin(),res.end());
return res;
}
};
本科时候写计算器的时候应该是写过类似的东西,把逆波兰的后序算式改成符合计算习惯的中序算式
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> operateNum;
for(string i : tokens){
if(i == "*"){
int lastNum = operateNum.top();
operateNum.pop();
int firstNum = operateNum.top();
operateNum.pop();
operateNum.push(firstNum * lastNum);
}else if(i == "+"){
int lastNum = operateNum.top();
operateNum.pop();
int firstNum = operateNum.top();
operateNum.pop();
operateNum.push(firstNum + lastNum);
}else if(i == "-"){
int lastNum = operateNum.top();
operateNum.pop();
int firstNum = operateNum.top();
operateNum.pop();
operateNum.push(firstNum - lastNum);
}else if(i == "/"){
int lastNum = operateNum.top();
operateNum.pop();
int firstNum = operateNum.top();
operateNum.pop();
operateNum.push(firstNum / lastNum);
}else{
operateNum.push(atoi(i.c_str()));
}
}
return operateNum.top();
}
};
这里一开始想用switch case的写法来替代这一大堆的if else,但是后面发现switch 表达式只能是整型或者可以转换为整型的数据,比如int,short,char这些,如float,double和string无法直接转int,不能充当表达式,算是查漏补缺了,以前一直没注意过这个事情
就酱