Leetcode20.有效的括号
class Solution {
public:
bool isValid(string s) {
stack<char> st;
for (int i = 0; i < s.size(); ++i) {
if (s[i] == '(' || s[i] == '{' || s[i] == '[') {
st.push(s[i]);
}
else {
if (s[i] == ')' && !st.empty() && st.top() == '(') {
st.pop();
}
else {
if (s[i] == ']' && !st.empty() && st.top() == '[') {
st.pop();
}
else {
if (s[i] == '}' && !st.empty() && st.top() == '{') {
st.pop();
}
else {
return false;
}
}
}
}
}
if (!st.empty()) return false;
return true;
}
};
Leetcode1047.删除字符串中的所有相邻重复项
class Solution {
public:
string removeDuplicates(string s) {
stack<char> st;
for (int i = 0; i < s.size(); ++i) {
if (st.empty() || st.top() != s[i]) {
st.push(s[i]);
}
else {
st.pop();
}
}
string result;
while (!st.empty()) {
result += st.top();
st.pop();
}
reverse(result.begin(), result.end());
return result;
}
};
Leetcode150.逆波兰表达式求值
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<long long> st;
for (int i = 0; i < tokens.size(); ++i) {
if (tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/") {
long long num1 = st.top();
st.pop();
long long num2 = st.top();
st.pop();
if (tokens[i] == "+") st.push(num2 + num1);
if (tokens[i] == "-") st.push(num2 - num1);
if (tokens[i] == "*") st.push(num2 * num1);
if (tokens[i] == "/") st.push(num2 / num1);
}
else {
st.push(stoll(tokens[i]));
}
}
return st.top();
}
};
我们今天实际上做的题目都是栈这个数据类型的实际应用
栈 意味这先入后出
这使得栈可以用来解决一种字符串或者数组内部的组合问题
1.有效括号 2.删除重复子串 3.逆波兰式