1、有效的括号
#include <iostream>
#include <stack>
using namespace std;
class Solution {
public:
bool isValid(string s) {
if (s.size() % 2 != 0) return false; // 如果s的长度为奇数,一定不符合要求
stack<char> st;
for (char i : s) {
if (i == '(') st.push(')');
else if (i == '{') st.push('}');
else if (i == '[') st.push(']');
// 第三种情况:遍历字符串匹配的过程中,栈已经为空了,没有匹配的字符了,说明右括号没有找到对应的左括号 return false
// 第二种情况:遍历字符串匹配的过程中,发现栈里没有我们要匹配的字符。所以return false
else if (st.empty() || st.top() != i) return false;
else st.pop(); // st.top() 与 s[i]相等,栈弹出元素
}
// 第一种情况:此时我们已经遍历完了字符串,但是栈不为空,说明有相应的左括号没有右括号来匹配,所以return false,否则就return true
return st.empty();
}
};
int main() {
string s = "({})[]";
Solution solution;
cout << solution.isValid(s) << endl;
}
2、删除字符串中的所有相邻重复项
用栈去实现:
#include <iostream>
#include <stack>
using namespace std;
class Solution {
public:
string removeDuplicates(const 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()) { //当栈st不为空时
result += st.top();
st.pop(); // 注意这个pop()函数没有返回值
}
reverse (result.begin(), result.end()); // 此时字符串需要反转一下
return result;
}
};
int main() {
string s = "abbaca";
Solution solution;
cout << solution.removeDuplicates(s) << endl;
}
直接用字符串去模拟栈的功能:
#include <iostream>
using namespace std;
class Solution {
public:
string removeDuplicates(const string& S) {
string result;
for(char s : S) {
if(result.empty() || result.back() != s) {
result.push_back(s);
}
else {
result.pop_back();
}
}
return result;
}
};
int main() {
string s = "abbaca";
Solution solution;
cout << solution.removeDuplicates(s) << endl;
}
3、逆波兰表达式求值
理解什么是后缀表达式,以及前序遍历、中序遍历和后序遍历
#include <iostream>
#include <stack>
using namespace std;
class Solution {
public:
int evalRPN(vector<string> &tokens) {
stack<int> st;
for (const auto & token : tokens) {
if (token == "+" || token == "-" || token == "*" || token == "/") {
int num1 = st.top();
st.pop();
int num2 = st.top();
st.pop();
if (token == "+") st.push(num2 + num1);
if (token == "-") st.push(num2 - num1);
if (token == "*") st.push(num2 * num1);
if (token == "/") st.push(num2 / num1);
} else {
st.push(stoi(token)); //把字符串string转化为整数int
}
}
int result = st.top();
st.pop(); // 把栈里最后一个元素弹出(其实不弹出也没事)
return result;
}
};
int main() {
vector<string> tokens = {"10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"};
Solution solution;
cout << solution.evalRPN(tokens) << endl;
}