LeetCode20.有效的括号
题目链接:https://leetcode.cn/problems/valid-parentheses/
思路:这里有三种不匹配的情况,
第一种情况,字符串里左方向的括号多余了 ,所以不匹配。
第二种情况,括号没有多余,但是 括号的类型没有匹配上。
第三种情况,字符串里右方向的括号多余了,所以不匹配。
第一种情况:已经遍历完了字符串,但是栈不为空,说明有相应的左括号没有右括号来匹配,所以return false。
第二种情况:遍历字符串匹配的过程中,发现栈里没有要匹配的字符。所以return false。
第三种情况:遍历字符串匹配的过程中,栈已经为空了,没有匹配的字符了,说明右括号没有找到对应的左括号return false。
那么什么时候说明左括号和右括号全都匹配了呢,就是字符串遍历完之后,栈是空的,就说明全都匹配了。
C++代码如下:
class Solution
{
public:
bool isValid(string s)
{
stack<char> stk_1;
if (s.size() % 2 != 0)
{
return false;
}
for (int i = 0; i < s.size(); i++)
{
int res1 = s[i];
if (stk_1.empty())
{
stk_1.push(res1);
}
else
{
if ((stk_1.top() == '('&&res1 == ')') || (stk_1.top() == '['&&res1 == ']') || (stk_1.top() == '{'&&res1 == '}'))
{
stk_1.pop();
}
else
{
stk_1.push(res1);
}
}
}
if (stk_1.empty())
{
return true;
}
else
return false;
}
};
LeetCode1047. 删除字符串中的所有相邻重复项
题目链接:https://leetcode.cn/problems/remove-all-adjacent-duplicates-in-string/
思路:使用栈来做。遍历字符串,存入栈中,每次获取字符串内的字符时,与栈顶的数值比较,若相同,则将当前获取的字符与栈顶的元素弹出,继续遍历字符串。
C++代码如下:
class Solution
{
public:
string removeDuplicates(string s)
{
stack<char> st1;
string result;
for(int i = 0; i < s.size(); i++)
{
if(st1.empty())
{
st1.push(s[i]);
}
else
{
char tmp = s[i];
if(st1.top() == tmp)
{
st1.pop();
}
else
{
st1.push(tmp);
}
}
}
while(!st1.empty())
{
char tmp = st1.top();
st1.pop();
result += tmp;
}
reverse(result.begin(), result.end());
return result;
}
};
LeetCode150. 逆波兰表达式求值
题目链接:https://leetcode.cn/problems/evaluate-reverse-polish-notation/
思路:使用栈来做,遍历字符串,存入栈中,碰到运算符则计算栈顶的两个值运算后的结果,再存入栈中。
C++代码如下:
class Solution
{
public:
int evalRPN(vector<string>& tokens)
{
stack<int> st1;
for(int i = 0; i < tokens.size(); i++)
{
if((tokens[i]=="+") || (tokens[i]=="-") || (tokens[i]=="*") || (tokens[i]=="/"))
{
int tmp01 = st1.top();
st1.pop();
int tmp02 = st1.top();
st1.pop();
if(tokens[i] == "+")
{
int tmp03 = tmp01 + tmp02;
st1.push(tmp03);
}
else if(tokens[i] == "-")
{
int tmp03 = tmp02 - tmp01;
st1.push(tmp03);
}
else if(tokens[i] == "*")
{
int tmp03 = tmp01 * tmp02;
st1.push(tmp03);
}
else if(tokens[i] == "/")
{
int tmp03 = tmp02 / tmp01;
st1.push(tmp03);
}
}
else
{
st1.push(stoi(tokens[i]));
}
}
int result = st1.top();
st1.pop();
return result;
}
};