目录
20.有效的括号
力扣:给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。有效字符串需满足:左括号必须用相同类型的右括号闭合、左括号必须以正确的顺序闭合、注意空字符串可被认为是有效字符串。
1、说明:括号匹配是使用栈解决的经典问题。
2、代码:
class Solution {
public:
bool isValid(string s) {
//用栈实现的经典题目
//如果字符串长度是奇数,括号一定无效
if(s.size()%2 != 0) return false;
stack<char> st;
for(int i=0;i<s.size();i++)
{
if(s[i] == '(') st.push(')');
else if(s[i] == '[') st.push(']');
else if(s[i] == '{') st.push('}');
else if( st.empty() || st.top()!=s[i] ) return false;
else st.pop();
}
if (st.empty()) return true;
else return false;
}
};
1047. 删除字符串中的所有相邻重复项
力扣:给出由小写字母组成的字符串 S,重复项删除操作会选择两个相邻且相同的字母,并删除它们。在 S 上反复执行重复项删除操作,直到无法继续删除。
1、代码:
class Solution {
public:
string removeDuplicates(string s) {
//用栈实现
stack<char> st;
for(char c: s)
{
if(st.empty() || c!=st.top()) st.push(c);
else st.pop();
}
string result = "";
while (!st.empty()) { // 将栈中元素放到result字符串汇总
result += st.top();
st.pop();
}
reverse (result.begin(), result.end()); // 此时字符串需要反转一下
return result;
}
};
150. 逆波兰表达式求值
力扣:根据 逆波兰表示法,求表达式的值。有效的运算符包括 + , - , * , / 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。说明:整数除法只保留整数部分。 给定逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。
1、关键:用栈做消除
2、补充:atoi(c)、stoi(c)、atof(c)、stof(c)
3、代码:
class Solution {
public:
int evalRPN(vector<string>& tokens) {
//逆波兰表达式用栈计算
stack<int> stk;
for(string c : tokens)
{
if(c =="+" || c =="-" ||c =="*" ||c =="/")
{
int nums1 = stk.top(); stk.pop();
int nums2 = stk.top(); stk.pop();
int res;
if(c=="+") res = nums2 + nums1;
else if(c=="-") res = nums2 - nums1;
else if(c=="*") res = nums2 * nums1;
else res = nums2 / nums1;
stk.push(res);
}
else stk.push(stoi(c));
}
return stk.top();
}
};