目录
代码随想录栈与队列理论基础
20. 有效的括号
文章讲解:代码随想录
class Solution {
public boolean isValid(String s) {
char[] array = s.toCharArray();
Stack<Character> stack = new Stack<>();
for(int i = 0;i<array.length;i++){
if(array[i]=='(' || array[i] =='{'||array[i]=='[')
stack.push(array[i]);
else{
if(!stack.isEmpty()){
if(array[i] == ')' && stack.peek() == '('){
stack.pop();
}else if(array[i] == '}' && stack.peek() == '{'){
stack.pop();
}else if(array[i] == ']' && stack.peek() == '['){
stack.pop();
}else
return false;
}else
return false;
}
}
if(stack.isEmpty())
return true;
return false;
}
}
1047. 删除字符串中的所有相邻重复项
文章讲解:代码随想录
class Solution {
public String removeDuplicates(String s) {
char[] c = s.toCharArray();
Stack<Character> stack = new Stack<>();
stack.push(c[0]);
for(int i = 1;i<c.length;i++){
if(stack.isEmpty()){
stack.push(c[i]);
}else{
if(c[i] == stack.peek()){
stack.pop();
}else{
stack.push(c[i]);
}
}
}
StringBuilder sb = new StringBuilder();
while(!stack.isEmpty()){
sb.append(stack.pop());
}
return sb.reverse().toString();
}
}
150. 逆波兰表达式求值
文章讲解:代码随想录
class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
int num1 = 0;
int num2 = 0;
for(int i = 0;i<tokens.length;i++){
if(tokens[i].equals("+") ){
num1 = stack.pop();
num2 = stack.pop();
stack.push(num1+num2);
}else if(tokens[i].equals("-")){
num1 = stack.pop();
num2 = stack.pop();
stack.push(num2-num1);
}else if(tokens[i].equals("*")){
num1 = stack.pop();
num2 = stack.pop();
stack.push(num1*num2);
}else if(tokens[i].equals("/")){
num1 = stack.pop();
num2 = stack.pop();
stack.push(num2/num1);
}else{
stack.push(Integer.parseInt(tokens[i]));
}
}
return stack.peek();
}
}