20. Valid Parentheses
这个题要注意几种false的情况;另外一个技巧是如果检测到左括号就往stack中加右括号,然后实时比较栈顶元素与检测到的元素是不是相等,相等就消消乐;
empty()返回的是false and true;
class Solution {
public:
bool isValid(string s) {
stack<char> result;
for(int i=0; i< s.size();i++){
if(s[i] == '(')
result.push(')');
else if(s[i] == '{')
result.push('}');
else if(s[i] == '[')
result.push(']');
else if(result.empty()||result.top()!=s[i])
return false;
else
result.pop();
}
// 第一种情况:此时我们已经遍历完了字符串,但是栈不为空,说明有相应的左括号没有右括号来匹配,所以return false,否则就return true
return result.empty();
}
};
1047. Remove All Adjacent Duplicates In String
那么栈的目的,就是存放遍历过的元素,当遍历当前的这个元素的时候,去栈里看一下我们是不是遍历过相同数值的相邻元素。同时要注意输出的要是string,不是stack,所以需要重新构建一个string;
class Solution {
public:
string removeDuplicates(string s) {
stack<char> result;
for(int i =0;i<s.size();i++){
if(result.empty()||s[i]!=result.top())
result.push(s[i]);
else if(s[i] ==result.top())
result.pop();
}
string true_result = "";
while(!result.empty()){
true_result += result.top(); // 注意c++中对string的+做了重载,可以连接起来字符成为字符串
result.pop(); //构造这个是因为需要输出一个字符串
}
reverse (true_result.begin(), true_result.end()); // 此时字符串需要反转一下
return true_result;
}
};
150. 逆波兰表达式求值
和上面那个消消乐的题差不多,差别是符合条件就不消消乐了,而是做加减乘除的运算
要注意下面这句
st.push(stoll(tokens[i]));
stoi 函数:将字符串转成 int 整数。
stol 函数:将字符串转成 long 整数。
stoll 函数:将字符串转成 long long 整数。