class Solution {
public boolean isValid(String s) {
if (s.length() % 2 != 0) return false;
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '(' || c == '[' || c == '{') {
stack.push(c);
} else if(c == ')' && !stack.isEmpty() && stack.peek() == '(') {
stack.pop();
} else if(c == ']' && !stack.isEmpty() && stack.peek() == '[') {
stack.pop();
} else if (c == '}' && !stack.isEmpty() && stack.peek() == '{') {
stack.pop();
} else {
return false;
}
}
return stack.isEmpty();
}
}
1047. 删除字符串中的所有相邻重复项 - 力扣(LeetCode)
class Solution {
public String removeDuplicates(String s) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (!stack.isEmpty() && stack.peek() == c) {
stack.pop();
} else {
stack.push(c);
}
}
StringBuilder sb = new StringBuilder();
while (!stack.isEmpty()){
sb.append(stack.pop());
}
return sb.reverse().toString();
}
}
class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for (String s : tokens) {
if (s.equals("+")) {
stack.push(stack.pop() + stack.pop());
} else if (s.equals("-")) {
int num1 = stack.pop();
int num2 = stack.pop();
stack.push(num2 - num1);
} else if (s.equals("*")) {
stack.push(stack.pop() * stack.pop());
} else if (s.equals("/")) {
int num1 = stack.pop();
int num2 = stack.pop();
stack.push(num2 / num1);
} else {
stack.push(Integer.valueOf(s));
}
}
return stack.pop();
}
}