Leetcode20. 有效的括号
题目链接:
思路:
考研备考时学过,比较简单,利用栈就行
class Solution {
public:
bool isValid(string s) {
stack<char> st;
for(int i=0;i<s.size();i++)
{
if(s[i]=='('||s[i]=='['||s[i]=='{')
{
st.push(s[i]);
}else{
if(st.empty())
{
return false;
}else{
if(s[i]==')'&&st.top()!='(')
{
return false;
}
if(s[i]==']'&&st.top()!='[')
{
return false;
}
if(s[i]=='}'&&st.top()!='{')
{
return false;
}
st.pop();
}
}
}
return st.empty();
}
};
Leetcode1047. 删除字符串中的所有相邻重复项
题目链接:
[1047. 删除字符串中的所有相邻重复项 - 力扣(Leetcode)]
思路:
同上,利用栈消除相同元素。注意:最后剩余的元素出栈是逆序,要调过来
class Solution {
public:
string removeDuplicates(string s) {
stack<char> st;
for(int i=0;i<s.size();i++)
{
if(st.empty()||s[i]!=st.top())
{
st.push(s[i]);
}else{
st.pop();
}
}
string res="";
while(!st.empty())
{
res+=st.top();
st.pop();
}
reverse(res.begin(),res.end());
return res;
}
};
Leetcode150. 逆波兰表达式求值
题目链接:
[150. 逆波兰表达式求值 - 力扣(Leetcode)]
思路:
每遇见一个运算符就弹出栈顶两个元素,计算后在入栈
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 int num1=st.top();
st.pop();
long long int num2=st.top();
st.pop();
if(tokens[i]== "+") st.push(num1+num2);
if(tokens[i]=="-") st.push(-num1+num2);
if(tokens[i]=="*") st.push(num1*num2);
if(tokens[i]=="/") st.push(num2/num1);
}
else{
st.push(stoll(tokens[i]));
}
}
int res=st.top();
return res;
}
};
总结
今天题目较简单,注意"a"
和'a'
的区别,前者是字符串,后者是字符。
stoll()
此函数将在函数调用中作为参数提供的字符串转换为long long int
。它解析str并将其内容解释为指定基数的整数,并将其作为long long int
类型的值返回。