20. 有效的括号
1.自己想的,直接入栈出栈同时匹配
bool isValid(string s) {
stack<char> st;
for (char& c : s)
{
switch(c)
{
case '(':
case '[':
case '{':
st.push(c);
break;
case ')':
if (!st.empty() && st.top() == '(') { st.pop();break; }
else return false;
case ']':
if (!st.empty() && st.top() == '[') { st.pop();break; }
else return false;
case '}':
if (!st.empty() && st.top() == '{') { st.pop();break; }
else return false;
default:
cout << 'invalid input!' << endl;
}
}
//最后不为空,则依然有错
return (st.empty());
}
2.代码随想录给出的方法
这个方法时在一开始就只传入反括弧,然后匹配的时候直接比较是否相等即可,省事
bool isValid(string s) {
stack<char> st;
//奇数一定不匹配
if (s.size() % 2 == 1) return false;
for (char& c : s)
{
if (c == '(') st.push(')');
else if (c == '[') st.push(']');
else if (c == '{') st.push('}');
else if (!st.empty() && st.top() == c) st.pop();
else return false;
}
return (st.empty());
}
1047. 删除字符串中的所有相邻重复项
一眼丁真,鉴定为栈去匹配
string removeDuplicates(string s) {
stack<char> st;
for (auto& c : s)
{
if (st.empty() || st.top() != c) st.push(c);
else st.pop();
}
string res;
while (!st.empty())
{
res.push_back(st.top());
st.pop();
}
reverse(res.begin(), res.end());
return res;
}
150. 逆波兰表达式求值
逆波兰表达式,也就是后缀表达式。它和中缀表达式的区别就是它将运算符号放在运算对象后,从而不需要括号来指明运算顺序。
同时,它也是最适合用栈来运算的表达式,每当遇到运算符,就取出前方的两个运算对象计算,将结果重新入栈,直至运算完成。
其实我们的中缀表达式也可以用栈去计算,只不过涉及到了括号,另外也涉及到了优先级的问题。中缀一般按照碰见更高优先级压入,碰见更低优先级弹出的逻辑
1.直白的写法
因为没有使用额外的方法,所以在把字符串变成数字上浪费了精力
int evalRPN(vector<string>& tokens) {
stack<int> num;
for (auto& s : tokens)
{
//如果是数字,直接push进数字栈
if (isdigit(s[0]) || (s.size() > 1 && isdigit(s[1])))
{
int tmp = 0;
if (s[0] == '-')
{
for (int i = 1; i < s.size(); i++)
{
tmp *= 10;
tmp += s[i] - '0';
}
tmp = -tmp;
}
else
{
for (auto& c : s)
{
tmp *= 10;
tmp += c - '0';
}
}
num.push(tmp);
}
else
{
int a, b;
a = num.top();
num.pop();
b = num.top();
num.pop();
switch(s[0])
{
case '+':
num.push(b + a);break;
case '-':
num.push(b - a);break;
case '*':
num.push(b * a);break;
case '/':
num.push(b / a);break;
default:
break;
}
}
}
return num.top();
}
2.代码随想录
实际上string类提供了==的重载,可以直接判断字符串是否相等,就不需要额外区分负数和减号
stoi函数可以将字符串转换为数字
int evalRPN(vector<string>& tokens) {
stack<int> st;
for (auto& s : tokens)
{
if (s == "+" || s == "-" || s == "*" || s == "/")
{
int a = st.top(); st.pop();
int b = st.top(); st.pop();
if (s == "+") st.push(b + a);
if (s == "-") st.push(b - a);
if (s == "*") st.push(b * a);
if (s == "/") st.push(b / a);
}
else
st.push(stoi(s));
}
return st.top();
}