class Solution {
public:
bool isValid(string s) {
stack<char> a;
if (s.size() % 2 != 0)
return false;
for (char i : s) {
if (i == '(' || i == '{' || i == '[') {
a.push(i);
}
if (a.empty())
return false;
if (a.top() == '{' && i == '}')
a.pop();
else if (a.top() == '(' && i == ')')
a.pop();
else if (a.top() == '[' && i == ']')
a.pop();
else if (a.top() != '(' && i == ')')
return false;
else if (a.top() != '[' && i == ']')
return false;
else if (a.top() != '{' && i == '}')
return false;
}
return a.empty();
}
};
1047. 删除字符串中的所有相邻重复项
class Solution {
public:
string removeDuplicates(string s) {
stack<char> a;
for (char i : s) {
if (a.empty() || a.top() != i)
a.push(i);
else
a.pop();
}
string z = "";
while (!a.empty()) {
z += a.top();
a.pop();
}
reverse(z.begin(),z.end());
return z;
}
};
150. 逆波兰表达式求值
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> a;
for (auto i : tokens) {
if (i == "+") {
int c = a.top();
a.pop();
int b = a.top();
a.pop();
a.push(b + c);
} else if (i == "*") {
int c = a.top();
a.pop();
int b = a.top();
a.pop();
a.push(b * c);
} else if (i == "-") {
int c = a.top();
a.pop();
int b = a.top();
a.pop();
a.push(b - c);
} else if (i == "/") {
int c = a.top();
a.pop();
int b = a.top();
a.pop();
a.push(b / c);
} else {
a.push(stoll(i));
}
}
return a.top();
}
};