目录
20. 有效的括号
代码:
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for(int i = 0; i < s.length(); i++){
char ch = s.charAt(i);
if(ch == '('){
stack.push(')');
}else if(ch == '['){
stack.push(']');
}else if(ch == '{'){
stack.push('}');
}else if(stack.isEmpty()|| stack.peek() != ch){
return false;
}else{
stack.pop();
}
}
return stack.isEmpty();
}
}
1047. 删除字符串中的所有相邻重复项
代码:
class Solution {
public String removeDuplicates(String s) {
Stack<Character> stack = new Stack<> ();
for ( int i = 0; i < s.length(); i ++){
char ch = s.charAt(i);
if(stack.isEmpty()|| stack.peek()!= ch){
stack.push(ch);
}else{
stack.pop();
}
}
String str = "";
while(!stack.isEmpty()){
str= stack.pop()+str;
}
return str;
}
}
150. 逆波兰表达式求值
代码:
class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for(String s : tokens){
if("+".equals(s)){
stack.push(stack.pop() + stack.pop());
}else if("-".equals(s)){
stack.push(-stack.pop() + stack.pop());
}else if("*".equals(s)){
stack.push(stack.pop() * stack.pop());
}else if("/".equals(s)){
int temp1 = stack.pop();
int temp2 = stack.pop();
stack.push(temp2 / temp1);
}else{
stack.push(Integer.valueOf(s));
}
}
return stack.pop();
}
}