20. Valid Parentheses
- 思路
- 先判断是否为空,为空也为true
- 然后遍历字符串 s.toCharArray
- 如果是open bace,就push进stack
- 如果不是,那先检查stack是否为空
- 为空则返回false
- 不为空的话跟栈顶元素比较一下,如果不配对,则返回false,配对则取出栈顶元素
-
//直接类似于暴力其实不难, class Solution { public boolean isValid(String s) { Stack<Character> stack = new Stack<>(); for(char c : s.toCharArray()){ if( stack.isEmpty() && (c ==')' || c== ']' || c== '}')){ return false; } if( !stack.isEmpty() && (c ==')' || c== ']' || c== '}') ){ char pre = stack.pop(); if( c == ')' && pre != '('){ return false; } else if( c =='}' && pre !='{'){ return false; } else if( c == ']' && pre != '['){ return false; } }else{ stack.push(c); } } return stack.isEmpty(); } }
1047. Remove All Adjacent Duplicates In String
- 挺简单的
-
java class Solution { public String removeDuplicates(String s) { Stack stack = new Stack<>(); StringBuilder sb = new StringBuilder(); for(int i = 0 ; i < s.length(); i++){ if(!stack.isEmpty() && stack.peek() == s.charAt(i)){ stack.pop(); }else{ stack.push(s.charAt(i)); } } for(char c : stack){ sb.append(c); } return sb.toString(); } }
150. Evaluate Reverse Polish Notation
也不难
class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for(String str : tokens){
if(!"+-*/".contains(str)){
int num = Integer.parseInt(str);
stack.push(num);
}else{
int num2 = stack.pop();
int num1 = stack.pop();
if(str.equals("+")){
stack.push(num2 + num1);
}else if(str.equals("-")){
stack.push(num1 - num2);
}else if (str.equals("*")){
stack.push(num1 * num2);
}else{
stack.push(num1 / num2);
}
}
}
return stack.pop();
}
}