20. Valid Parentheses
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
- Every close bracket has a corresponding open bracket of the same type.
题目解析:
- 使用栈来模拟open bracket 和 close bracket 抵消
代码:
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 == '(') {
stack.push(')');
} else if (c == '[') {
stack.push(']');
} else if (c == '{') {
stack.push('}');
} else {
if (stack.size() == 0 || stack.pop() != c) {
return false;
}
}
}
if (stack.size() > 0) {
return false;
}
return true;
}
1047. Remove All Adjacent Duplicates In String
You are given a string s consisting of lowercase English letters. A duplicate removal consists of choosing two adjacent and equal letters and removing them.
We repeatedly make duplicate removals on s until we no longer can.
Return the final string after all such duplicate removals have been made. It can be proven that the answer is unique.
题目解析:
- 与上题类似,使用栈
代码:
class Solution {
public String removeDuplicates(String s) {
Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()) {
if (stack.size() > 0 && stack.peek() == c) {
stack.pop();
} else {
stack.push(c);
}
}
char[] arr = new char[stack.size()];
for (int i = arr.length - 1; i >= 0; i--) {
arr[i] = stack.pop();
}
return new String(arr);
}
}
150. Evaluate Reverse Polish Notation
You are given an array of strings tokens that represents an arithmetic expression in a Reverse Polish Notation.
Evaluate the expression. Return an integer that represents the value of the expression.
Note that:
- The valid operators are
'+','-','*', and'/'. - Each operand may be an integer or another expression.
- The division between two integers always truncates toward zero.
- There will not be any division by zero.
- The input represents a valid arithmetic expression in a reverse polish notation.
- The answer and all the intermediate calculations can be represented in a 32-bit integer.
题目解析:
- 出现操作是,需要用前两个数算出结果再加入栈中
代码:
class Solution {
public int evalRPN(String[] tokens) {
Set<String> operators = new HashSet<>(Arrays.asList("+", "-", "*", "/"));
Stack<String> stack = new Stack<>();
for (String token : tokens) {
if (!operators.contains(token)) {
stack.push(token);
} else {
int right = Integer.parseInt(stack.pop());
int left = Integer.parseInt(stack.pop());
if ("+".equals(token)) {
stack.push(String.valueOf(left + right));
} else if ("-".equals(token)) {
stack.push(String.valueOf(left - right));
} else if ("*".equals(token)) {
stack.push(String.valueOf(left * right));
} else if ("/".equals(token)) {
stack.push(String.valueOf(left / right));
}
}
}
return Integer.parseInt(stack.pop());
}
}