目录
题目1: 20. 有效的括号
- 题目链接:
1- 思路
- 利用栈来判断括号是否有效
思路
- 遇到 ( [ { 三种左括号时候,将其对应的右括号入栈,当遇到右括号时,则弹出 和 弹出的括号比较
- 匹配则继续,不匹配则 返回 false,证明无效
2- 题解
⭐用栈实现队列 ——题解思路
class Solution {
public boolean isValid(String s) {
int len = s.length();
Stack<Character> stack = new Stack<>();
for(int i = 0 ; i < len;i++){
if(s.charAt(i)=='['){
stack.push(']');
}else if(s.charAt(i)=='('){
stack.push(')');
}else if(s.charAt(i)=='{'){
stack.push('}');
}else if(stack.isEmpty() || stack.peek()!=s.charAt(i)){
return false;
}else{
stack.pop();
}
}
return stack.isEmpty();
}
}
题目2: 1047. 删除字符串中的所有相邻重复项
- 题目链接:
1- 思路
- 思路类似于 括号匹配
2-题解
⭐删除字符串中的所有相邻重复项 ——题解思路
class Solution {
public String removeDuplicates(String s) {
int len = s.length();
Stack<Character> st = new Stack<>();
StringBuilder sb = new StringBuilder();
for(int i = 0 ; i < len;i++){
char c = s.charAt(i);
if(st.isEmpty() || c!=st.peek()){
st.push(c);
}else{
st.pop();
}
}
String res="";
while(!st.isEmpty()){
char c = st.pop();
res = c+res;
}
return res;
}
}
题目3: 150. 逆波兰表达式求值
- 题目链接:150. 逆波兰表达式求值
1- 思路
- 借助队列来存储值,如果遇到的是四种符号,则直接做计算。
- 栈存储的结果为遍历到的值,或匹配到符号后弹出的两个值的计算结果
#
2- 题解
⭐逆波兰表达式求值 ——题解思路
class Solution {
public int evalRPN(String[] tokens) {
int len = tokens.length;
Stack<Integer> st = new Stack<>();
for(int i = 0 ; i < len;i++){
String c = tokens[i];
if(c.equals("+")){
int n1 = st.pop();
int n2 = st.pop();
st.push(n1+n2);
}else if(c.equals("-")){
int n1 = st.pop();
int n2 = st.pop();
st.push(n2-n1);
}else if(c.equals("*")){
int n1 = st.pop();
int n2 = st.pop();
st.push(n2*n1);
}else if(c.equals("/")){
int n1 = st.pop();
int n2 = st.pop();
st.push(n2/n1);
}else{
st.push(Integer.valueOf(c));
}
}
return st.pop();
}
}