20. 有效的括号
https://leetcode.cn/problems/valid-parentheses/submissions/497737377/
class Solution {
public boolean isValid(String s) {
int n = s.length();
if (n % 2 == 1) {
return false;
}
Map<Character, Character> pairs = new HashMap<Character, Character>() {{
put(')', '(');
put(']', '[');
put('}', '{');
}};
Deque<Character> stack = new LinkedList<Character>();
for(int i = 0 ; i < n ; i++){
char ch = s.charAt(i);
if(pairs.containsKey(ch)){
if(stack.isEmpty() || stack.peek() != pairs.get(ch)){
return false;
}
stack.pop();
}else{
stack.push(ch);
}
}
return stack.isEmpty();
}
}
1047. 删除字符串中的所有相邻重复项
https://leetcode.cn/problems/remove-all-adjacent-duplicates-in-string/description/
class Solution {
public String removeDuplicates(String s) {
ArrayDeque<Character> deque = new ArrayDeque<>();
char ch ;
for(int i = 0; i < s.length(); i++){
ch = s.charAt(i);
if(deque.isEmpty() || deque.peek() != ch){
deque.push(ch);
}else{
deque.pop();
}
}
String str = "";
while(!deque.isEmpty()){
str=deque.pop()+str;
}
return str;
}
}
150. 逆波兰表达式求值
https://leetcode.cn/problems/8Zf90G/description/
class Solution {
public int evalRPN(String[] tokens) {
Deque<Integer> stack = new LinkedList<Integer>();
int n = tokens.length;
for(int i = 0 ; i < n ; i++){
String token = tokens[i];
if(isNumber(token)){
stack.push(Integer.parseInt(token));
}else{
int num2 = stack.pop();
int num1 = stack.pop();
switch(token){
case"+":
stack.push(num1+num2);
break;
case"-":
stack.push(num1-num2);
break;
case"*":
stack.push(num1*num2);
break;
case"/":
stack.push(num1/num2);
break;
default:
}
}
}
return stack.pop();
}
public boolean isNumber(String token) {
return !("+".equals(token) || "-".equals(token) || "*".equals(token) || "/".equals(token));
}
}