20. 有效的括号
1047. 删除字符串中的所有相邻重复项
150. 逆波兰表达式求值
20. 有效的括号
解题思路:
栈机制:遍历字符串,遇到左括号压栈,遇到右括号判断:若有与之匹配的左括号,弹栈,若不匹配,直接返回false
遍历完字符串,判断栈空,若空,返回true;否则,返回false
class Solution {
public:
bool isValid(string s)
{
if (s.size() % 2 != 0) {
return false;
}
stack<char> stk;
for (auto c : s) {
if (stk.empty()) {
stk.push(c);
} else {
char e = 0;
if (c == ')') {
e = '(';
} else if (c == ']') {
e = '[';
} else if (c == '}') {
e = '{';
} else {
stk.push(c);
continue;
}
char t = stk.top();
if (e == t) {
stk.pop();
} else {
return false;
}
}
}
return stk.empty();
}
};
1047. 删除字符串中的所有相邻重复项
解题思路:
我这里借助了栈,把字母塞进去,如果下一个和上一个相同就出栈,不然就入栈,最后借助 reverse 转置一下,生成字符串。
class Solution {
public:
string removeDuplicates(string S) {
stack<char> st;
for (char s : S) {
if (st.empty() || s != st.top()) {
st.push(s);
} else {
st.pop(); // s 与 st.top()相等的情况
}
}
string result = "";
while (!st.empty()) { // 将栈中元素放到result字符串汇总
result += st.top();
st.pop();
}
reverse (result.begin(), result.end()); // 此时字符串需要反转一下
return result;
}
};
150. 逆波兰表达式求值
逆波兰表达式:
逆波兰表达式是一种后缀表达式,所谓后缀就是指算符写在后面。
平常使用的算式则是一种中缀表达式,如 ( 1 + 2 ) * ( 3 + 4 ) 。
该算式的逆波兰表达式写法为 ( ( 1 2 + ) ( 3 4 + ) * ) 。
逆波兰表达式主要有以下两个优点:
去掉括号后表达式无歧义,上式即便写成 1 2 + 3 4 + * 也可以依据次序计算出正确结果。
适合用栈操作运算:遇到数字则入栈;遇到算符则取出栈顶两个数字进行计算,并将结果压入栈中
解题思路:
1、将字符串添加到集合中
2、创建栈 用来当计算容器
3、遍历集合元素 如果是数字则直接入栈;当遇到符号时 pop出两个数 进行计算 将计算后的结果再入栈
4、返回最后栈中的元素,就是计算的结果
int evalRPN(vector<string>& tokens) {
stack<string> sta;
for (string t : tokens) {
if (t == "+") {
string temp1 = sta.top();
sta.pop();
string temp2 = sta.top();
sta.pop();
//stoi() 将 n 进制的字符串转化为十进制
int result = stoi(temp2) + stoi(temp1);
sta.push(to_string(result));
}
else if (t == "-") {
string temp1 = sta.top();
sta.pop();
string temp2 = sta.top();
sta.pop();
int result = stoi(temp2) - stoi(temp1);
sta.push(to_string(result));
}
else if (t == "*") {
string temp1 = sta.top();
sta.pop();
string temp2 = sta.top();
sta.pop();
int result = stoi(temp2) * stoi(temp1);
sta.push(to_string(result));
}
else if (t == "/") {
string temp1 = sta.top();
sta.pop();
string temp2 = sta.top();
sta.pop();
int result = stoi(temp2) / stoi(temp1);
sta.push(to_string(result));
}
else {
sta.push(t);
}
}
return stoi(sta.top());
}