day11
相对比较简单
20. 有效的括号
自己写的,
class Solution {
public:
bool isValid(string s) {
stack<char> st;
int i = 0;
while (i < s.size()) {
if (s[i]=='(' || s[i]=='{' || s[i]=='[') {
st.push(s[i]);
i++;
}
else if (!st.empty() && ((s[i] == ')' && st.top() == '(') || (s[i] == '}' && st.top() == '{') || (s[i] == ']' && st.top() == '['))) {
st.pop();
i++;
}
else return false;
}
if (st.empty() && i == s.size()) return true;
else return false;
}
};
Karl的,在入栈的时候就放的是右括号,省下了繁琐的比较判断(从人的视角来看)。
class Solution {
public:
bool isValid(string s) {
if (s.size() % 2 != 0) return false; // 如果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(']');
// 第三种情况:遍历字符串匹配的过程中,栈已经为空了,没有匹配的字符了,说明右括号没有找到对应的左括号 return false
// 第二种情况:遍历字符串匹配的过程中,发现栈里没有我们要匹配的字符。所以return false
else if (st.empty() || st.top() != s[i]) return false;
else st.pop(); // st.top() 与 s[i]相等,栈弹出元素
}
// 第一种情况:此时我们已经遍历完了字符串,但是栈不为空,说明有相应的左括号没有右括号来匹配,所以return false,否则就return true
return st.empty();
}
};
1047. 删除字符串中的所有相邻重复项
class Solution {
public:
string removeDuplicates(string s) {
stack<char> st;
for (int i = 0; i < s.size(); i++) {
if (!st.empty() && s[i] == st.top()) {
st.pop();
} else {
st.push(s[i]);
}
}
string res;
while (!st.empty()) {
res.push_back(st.top());
st.pop();
}
reverse(res.begin(), res.end());
return res;
}
};
以及string本身就有push_back()
和pop_back()
方法,直接拿res当栈用。
150. 逆波兰表达式求值
逆波兰表达式:是一种后缀表达式,所谓后缀就是指运算符写在后面。
平常使用的算式则是一种中缀表达式,如 ( 1 + 2 ) * ( 3 + 4 ) 。
该算式的逆波兰表达式写法为 ( ( 1 2 + ) ( 3 4 + ) * ) 。
逆波兰表达式主要有以下两个优点:
- 去掉括号后表达式无歧义,上式即便写成 1 2 + 3 4 + * 也可以依据次序计算出正确结果。
- 适合用栈操作运算:遇到数字则入栈;遇到运算符则取出栈顶两个数字进行计算,并将结果压入栈中。
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> st;
for (string s: tokens) {
if (s=="+" || s=="-" || s=="*" || s=="/") {
int n2 = st.top();
st.pop();
int n1 = st.top();
st.pop();
int tmp = 0;
// 这里不能用switch来判断string,可能因为string不是基本的数据类型
if (s == "+") tmp = n1 + n2;
else if (s == "-") tmp = n1 - n2;
else if (s == "*") tmp = n1 * n2;
else if (s == "/") tmp = n1 / n2;
st.push(tmp);
}else {
// 字符串怎么转为整数
st.push(stoi(s));
}
}
return st.top();
}
};