今日题目较易,多多感悟栈的奥妙
Leetcode 20. 有效的括号
链接:20. 有效的括号
thought:
- 括号匹配是使用栈解决的经典问题。
- 由于栈结构的特殊性,非常适合做对称匹配类的题目。
- 思路:我们可以遍历字符串,在这个过程中,遇到左括号字符时,让其对应的右括号字符进入栈,当遇到右括号字符时,和栈顶比较。
- 分析:有三种不匹配的情况
- 左括号多余了
- 括号无多余,但括号类型不匹配
- 右括号多余了
完整C++代码如下:
//时间复杂度: O(n)
//空间复杂度: O(n)
class Solution {
public:
bool isValid(string s) {
// 剪枝
if (s.size() % 2 == 1)
return false;
stack<char> str;
for (char t : s) {//可以使用int i,速度快一点
if (t == '(') {
str.push(')');
} else if (t == '{') {
str.push('}');
} else if (t == '[') {
str.push(']');
} else {
if (str.empty() || t != str.top()) {
return false;
} else {
str.pop();
}
}
}
return str.empty();
}
};
Leetcode 1047. 删除字符串中的所有相邻重复项
thought:
栈可以利用top()函数始终记录上一个元素
完整C++代码如下:
//时间复杂度: O(n)
//空间复杂度: O(n)
class Solution {
public:
string removeDuplicates(string s) {
stack<char> st;
st.push(s[0]);
for (int i = 1; i < s.size(); i++) {
if (!st.empty() && s[i] == st.top()) {
st.pop();
} else
st.push(s[i]);
}
string res;
while (!st.empty()) {
res += st.top();
st.pop();
}
reverse(res.begin(), res.end());
return res;
}
};
Leetcode 150. 逆波兰表达式求值
thought:
-
直接设置int型栈而不是string型
-
注意两种if在何时使用,看似重复但节省了大量操作
-
stoll( ):是一个标准库函数,用于将字符串转换为长整型(
long long int
)。当确定一个std::string
对象内部存储的是一个可以解析为long long int
的数值时,可以使用此函数进行转换。
完整C++代码如下:
//时间复杂度: O(n)
//空间复杂度: O(n)
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]));
}
}
int result = st.top();
st.pop(); // 把栈里最后一个元素弹出
return result;
}
};