20. 有效的括号
先贴代码:
bool isValid(string s) {
stack<char> box;
for(char c : s){
if(box.empty()){
box.push(c);
continue;
}else if( c == ')' && box.top() == '('){
box.pop();
continue;
}else if( c == '}' && box.top() == '{'){
box.pop();
continue;
}else if( c == ']' && box.top() == '['){
box.pop();
continue;
}else box.push(c);
}
return box.empty();
}
1047. 删除字符串中的所有相邻重复项
我的代码:
string removeDuplicates(string s) {
stack<char> box;
string res;
for(char c : s){
if(box.empty()) box.push(c);
else if( c == box.top()) box.pop();
else box.push(c);
}
while(!box.empty()){
res += box.top();
box.pop();
}
reverse(res.begin(),res.end());
return res;
}
心得:
刚开始 用的是append函数,但是append不能直接对 char 进行操作,他只能对 string 进行操作且会修改被添加的字符串。
以及对字符串进行翻转用的是的 reverse 函数。
swap只是单纯变换俩个变量的值,如果在这里面用的话,需要加一个循环。
150. 逆波兰表达式求值
贴代码:
int evalRPN(vector<string>& tokens) {
stack<long long> box;
for(int i = 0; i < tokens.size(); i++){
if(tokens[i]=="+" || tokens[i]=="-" || tokens[i]=="*" || tokens[i]=="/"){
long long num1 = box.top();
box.pop();
long long num2 = box.top();
box.pop();
if(tokens[i] == "+") box.push(num2 + num1);
if(tokens[i] == "-") box.push(num2 - num1);
if(tokens[i] == "*") box.push(num2 * num1);
if(tokens[i] == "/") box.push(num2 / num1);
}else box.push(stoll(tokens[i]));
}
return box.top();
}
心得体会:
为了迎合数据大小,改成 long long , 且需要将字符串转成 long long 形式,而且别弄错,num2 和 num1 ,到底谁÷ 谁,这个别弄反了
以及不要忘了 , ' '对应字符, “ ” 对应字符串。