20. 有效的括号
讲完了栈实现队列,队列实现栈,接下来就是栈的经典应用了。
大家先自己思考一下 有哪些不匹配的场景,在看视频 我讲的都有哪些场景,落实到代码其实就容易很多了。题目链接/文章讲解/视频讲解。
由于括号匹配的问题,利用栈FILO的特点实现。
Python版本:
class Solution:
def isValid(self, s: str) -> bool:
p_dict = {')':'(', '}':'{', ']':'['}
stk = []
for k in s:
if not k in p_dict.keys():
stk.append(k)
else:
if len(stk)==0:
return False
v = stk.pop()
if p_dict[k] != v:
return False
return len(stk)==0
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(']');
} else if (st.empty() || st.top()!=s[i]) {
return false;
} else {
st.pop();
}
}
return st.empty();
}
};
1047. 删除字符串中的所有相邻重复项
栈的经典应用。
要知道栈为什么适合做这种类似于爱消除的操作,因为栈帮助我们记录了 遍历数组当前元素时候,前一个元素是什么。题目链接/文章讲解/视频讲解。
Python版本:
class Solution:
def removeDuplicates(self, s: str) -> str:
stk = []
prev = None
for cur in s:
stk.append(cur)
while len(stk)>=2 and stk[-1]==stk[-2]:
stk = stk[:-2]
return "".join(stk)
C++版本:
字符串可以直接作为栈。
class Solution {
public:
string removeDuplicates(string s) {
string result;
for (int i=0; i<s.size(); i++) {
if (result.empty() || result.back()!=s[i]) {
result.push_back(s[i]);
} else {
result.pop_back();
}
}
return result;
}
};
150. 逆波兰表达式求值
本题不难,但第一次做的话,会很难想到,所以先看视频,了解思路再去做题。题目链接/文章讲解/视频讲解。
Python版本:
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
op_set = set(['+', '-', '*', '/'])
stk = []
for cur in tokens:
if cur in op_set:
num2 = stk.pop()
num1 = stk.pop()
exp = num1 + cur + num2
ans = int(eval(exp))
stk.append(str(ans))
else:
stk.append(cur)
return int(stk[0])
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 result = st.top();
st.pop();
return result;
}
};