20. 有效的括号
20. Valid Parentheseshttps://leetcode.com/problems/valid-parentheses/
题目要求: 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
- 注意空字符串可被认为是有效字符串。
括号匹配是使用栈解决的经典问题。
如果还记得编译原理的话,编译器在词法分析的过程中处理括号、花括号等这个符号的逻辑,也是使用了栈这种数据结构。
首先要弄清楚,字符串里的括号不匹配有几种情况。
先来分析一下 这里有三种不匹配的情况,
-
第一种情况,字符串里左方向的括号多余了 ,所以不匹配。
2. 第二种情况,括号没有多余,但是括号的类型没有匹配上。
3. 第三种情况,字符串里右方向的括号多余了,所以不匹配。
第一种情况:已经遍历完了字符串,但是栈不为空,说明有相应的左括号没有右括号来匹配,所以return false;
第二种情况:遍历字符串匹配的过程中,发现栈里没有要匹配的字符。所以return false;(括号的类型没有匹配上)
第三种情况:遍历字符串匹配的过程中,栈已经为空了,没有匹配的字符了,说明右括号没有找到对应的左括号return false;
C++:
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(']');
// 第三种情况:遍历字符串匹配的过程中,栈已经为空了,没有匹配的字符了,
// 说明右括号没有找到对应的左括号 return false
// 第二种情况:遍历字符串匹配的过程中,发现栈里没有我们要匹配的字符。所以return false
else if (st.empty() || st.top() != s[i]) return false;
else st.pop();
}
// 第一种情况:此时我们已经遍历完了字符串,但是栈不为空,
// 说明有相应的左括号没有右括号来匹配,所以return false,否则就return true
return st.empty();
}
};
- 时间复杂度: O(n)
- 空间复杂度: O(n)
Python:
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = []
for item in s:
if item =='(':
stack.append(')')
elif item == '[':
stack.append(']')
elif item == '{':
stack.append('}')
elif not stack or stack[-1] != item:
return False
else:
stack.pop()
return True if not stack else False
1047. 删除字符串中的所有相邻重复项
1047. Remove All Adjacent Duplicates In Stringhttps://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/题目要求:给出由小写字母组成的字符串 S,重复项删除操作会选择两个相邻且相同的字母,并删除它们。
在 S 上反复执行重复项删除操作,直到无法继续删除。
在完成所有重复项删除操作后返回最终的字符串。答案保证唯一。
本题要删除相邻相同元素,相对于20. 有效的括号 (opens new window)来说其实也是匹配问题,20. 有效的括号 是匹配左右括号,本题是匹配相邻元素,最后都是做消除的操作。
和括号匹配的逻辑是类似的,考察栈顶元素是否和当前元素相同,如果相同就删除,不同就把新的元素压入栈。
C++:
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 res = "";
while (!st.empty()){
res += st.top();
st.pop();
}
reverse(res.begin(), res.end());
return res;
}
};
- 时间复杂度: O(n)
- 空间复杂度: O(n)
C++(用字符串直接作为栈):
class Solution {
public:
string removeDuplicates(string s) {
string res;
for (char c : s){
if (res.empty() || res.back() != c){
res.push_back(c);
}
else{
res.pop_back();
}
}
return res;
}
};
- 时间复杂度: O(n)
- 空间复杂度: O(1),返回值不计空间复杂度
Python:
class Solution(object):
def removeDuplicates(self, s):
"""
:type s: str
:rtype: str
"""
res = []
for item in s:
if res and res[-1] == item:
res.pop()
else:
res.append(item)
return "".join(res)
150. 逆波兰表达式求值
150. Evaluate Reverse Polish Notationhttps://leetcode.com/problems/evaluate-reverse-polish-notation/题目要求:根据 逆波兰表示法,求表达式的值。
有效的运算符包括 + , - , * , / 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。
说明:
整数除法只保留整数部分。 给定逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。
示例 1:
- 输入: ["2", "1", "+", "3", " * "]
- 输出: 9
- 解释: 该算式转化为常见的中缀算术表达式为:((2 + 1) * 3) = 9
示例 2:
- 输入: ["4", "13", "5", "/", "+"]
- 输出: 6
- 解释: 该算式转化为常见的中缀算术表达式为:(4 + (13 / 5)) = 6
逆波兰表达式定义
是一种后缀表达式,所谓后缀就是指运算符写在后面。
平常使用的算式则是一种中缀表达式,如 ( 1 + 2 ) * ( 3 + 4 ) 。
该算式的逆波兰表达式写法为 ( ( 1 2 + ) ( 3 4 + ) * ) 。
逆波兰表达式主要有以下两个优点:
-
去掉括号后表达式无歧义,上式即便写成 1 2 + 3 4 + * 也可以依据次序计算出正确结果。
-
适合用栈操作运算:遇到数字则入栈;遇到运算符则取出栈顶两个数字进行计算,并将结果压入栈中。
栈与递归之间在某种程度上是可以转换的! 这一点我们在后续讲解二叉树的时候,会更详细的讲解到。
在进一步看,本题中每一个子表达式要得出一个结果,然后拿这个结果再进行运算,那么这岂不就是一个相邻字符串消除的过程,和1047.删除字符串中的所有相邻重复项 (opens new window)中的对对碰游戏是不是就非常像了。
C++:
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 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 res = st.top();
return res;
}
};
Python(Python中的除法与C++中不太一样):
from operator import add, sub, mul
import math
class Solution:
def custom_div(x, y):
if y == 0:
return float('inf') # 或者其他你想返回的值
if x * y > 0:
return x // y
else:
return -(-x // y)
op_map = {'+': add, '-': sub, '*': mul, '/': custom_div}
def evalRPN(self, tokens):
if not tokens:
return None
stack = []
for token in tokens:
if token not in {'+', '-', '*', '/'}:
stack.append(int(token))
else:
op2 = stack.pop()
op1 = stack.pop()
stack.append(self.op_map[token](op1, op2)) # 第一个出来的在运算符后面
print(stack[-1])
return stack.pop()