20. 有效的括号
题目链接/文章讲解/视频讲解:链接地址
代码思路:利用栈的先进后出原则,分析题目可知,如果遍历字符串,往栈压字符,必定是成对的出现在栈里面,这种思维类似与消消乐,如果栈里面没有成对出现的字符,就返回false,最后栈里面都是空返回true.
class Solution {
public:
bool isValid(string s) {
stack<char> tempStack;
if (s.size() % 2 != 0) {
return false;
}
for (int i = 0; i < s.size(); i++) {
if (s[i] == '(') tempStack.push(')');
else if (s[i] == '[') tempStack.push(']');
else if (s[i] == '{') tempStack.push('}');
else if (tempStack.empty() || tempStack.top() != s[i]) return false;
else tempStack.pop();
}
if (tempStack.empty()) {
return true;
} else {
return false;
}
}
};
1047. 删除字符串中的所有相邻重复项
题目链接/文章讲解/视频讲解:链接地址
代码思路:创建一个栈,遍历整个字符串,与栈顶的数据进行对比,如果相同就pop出来,如果不同就push进栈。最后对栈里面剩余的元素反转返回就是结果。
class Solution {
public:
string removeDuplicates(string s) {
stack<char> tempStack;
for (int i = 0; i < s.size(); i++) {
if (tempStack.empty() || tempStack.top() != s[i]) {
tempStack.push(s[i]);
} else {
tempStack.pop();
}
}
string result = "";
while (!tempStack.empty()) {
result += tempStack.top();
tempStack.pop();
}
reverse (result.begin(), result.end());
return result;
}
};
150. 逆波兰表达式求值
题目链接/文章讲解/视频讲解:链接地址
代码思路:通过观察分析得出,数组里面的元素遇到数学运算符号的时候就将运算符号前面的两个进行相应的运算,因此可以通过栈的特性来实现代码。
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<long long> tempStack;//测试用例需要用到这么大的数据类型
for (int i = 0; i < tokens.size(); i++) {
if (tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/") {
long long nums1 = tempStack.top();
tempStack.pop();
long long nums2 = tempStack.top();
tempStack.pop();
if (tokens[i] == "+") tempStack.push(nums2 + nums1);
if (tokens[i] == "-") tempStack.push(nums2 - nums1);
if (tokens[i] == "*") tempStack.push(nums2 * nums1);
if (tokens[i] == "/") tempStack.push(nums2 / nums1);// 注意是nums2 在前面
} else {
tempStack.push(stoll(tokens[i]));
}
}
int result = tempStack.top();
return result;
}
};