leetcode 20 有效的括号
public static boolean isValid(String s){
//Deque<Character> stack = new LinkedList<>();
ArrayDeque<Character> stack = new ArrayDeque<>();
if(s.length()%2!=0) return false;
for (int i = 0; i < s.length(); i++) {
switch (s.charAt(i)) {
case '{':
stack.push('}');
break;
case '(':
stack.push(')');
break;
case '[':
stack.push(']');
break;
case '}':
case ']':
case ')':
if (stack.size() == 0 || stack.peek() != s.charAt(i)) { // 和栈顶元素比对
return false;
} else {
stack.pop();
break;
}
}
}
if(stack.size()!=0) return false;
return true;
}
leetcode 1047 删除相同相邻字符
public static String removeDuplicates(String s){
String result ="";
Deque<Character> stack = new LinkedList<>();
//ArrayDeque<Character> stack = new ArrayDeque<>();
for(int i =0;i< s.length();i++){
if(stack.size()==0) {
stack.push(s.charAt(i));
continue;
}
if(stack.peek()==s.charAt(i))
stack.pop();
else
stack.push(s.charAt(i));
}
while(!stack.isEmpty()){
result = stack.pop() + result;
}
return result;
}
leetcode 150 逆波兰表达式
public static int evalRPN(String[] tokens){
int result=0;
Deque<Integer> stack = new LinkedList<>();
String tmp =null;
for(int i=0;i<tokens.length;i++){
tmp = tokens[i];
if(tmp=="+"){
result = stack.pop() + stack.pop();
stack.push(result);
}else if(tmp.equals("-")){
result = -stack.pop() + stack.pop();
stack.push(result);
}else if(tmp.equals("*")){
result = stack.pop() * stack.pop();
stack.push(result);
} else if (tmp.equals("/")) {
int tmp11= stack.pop();
int tmp12= stack.pop();
result = tmp12/tmp11;
stack.push(result);
} else {
stack.push(Integer.valueOf(tokens[i]));
}
}
return result;
}