20. 有效的括号
题目描述
解题思路
典型的使用栈的题目
class Solution {
public:
bool isValid(const string &s) {
stack<char> c;//创建一个栈
for(const char &i:s){//const char &防深拷贝,foreach循环不用考虑越界
if(i=='('||i=='{'||i=='['){//若为左大、中、小括号
c.push(i);//入栈
}else if(!c.empty() && ((i==')'&&c.top()=='(')
|| (i=='}'&&c.top()=='{')
|| (i==']'&&c.top()=='['))){//当前栈不为空,且栈顶和右括号成对出现
c.pop();//出栈
}else{//若右括号遇到栈为空,或栈顶不匹配
return false;
}
}
return c.empty();//当前栈是否为空
}
};
1047. 删除字符串中的所有相邻重复项
题目描述
解题思路
解法1 栈
class Solution {
public:
string removeDuplicates(string s) {
stack<char>temp;
for(char c:s)
{
if(temp.empty()||c != temp.top())
{
temp.push(c);
}
else
{
temp.pop();
}
}
string ans;
while(!temp.empty())
{
ans += temp.top();
temp.pop();
}
reverse(ans.begin(),ans.end());
return ans;
}
};
解法2 双指针
class Solution {
public:
string removeDuplicates(string s) {
int slow = 0, fast = 0;
while(fast<s.size())
{
s[slow] = s[fast];
if(slow>0&&s[slow] == s[slow-1])
{
slow--;
}
else{
slow++;
}
fast++;
}
string ans(s.begin(),s.begin()+slow);
return ans;
}
};
解法3 用string模拟栈
由于 std::string\texttt{std::string}std::string 类本身就提供了类似「入栈」和「出栈」的接口,因此可以直接将需要被返回的字符串作为栈即可。
class Solution {
public:
string removeDuplicates(string s) {
string ans;
for(char c : s)
{
if(ans.empty()|| ans.back()!=c)
{
ans.push_back(c);
}
else
{
ans.pop_back();
}
}
return ans;
}
};
150. 逆波兰表达式求值
题目描述
解题思路
class Solution {
public:
int evalRPN(vector<string>& tokens) {
// 力扣修改了后台测试数据,需要用longlong
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;
}
};