day11 打卡20. 有效的括号 1047. 删除字符串中的所有相邻重复项 150. 逆波兰表达式求值
20. 有效的括号
1.本来使用的是Stack,时间2 ms,内存39.6 MB。而Deque时间1 ms,内存39.7 MB。
class Solution {
public boolean isValid(String s) {
if (s.length() % 2 != 0) return false;
Deque<Character> stack = new LinkedList<Character>();
char ch;
for (int i = 0 ; i<s.length() ; i++) {
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();
}
}
if (!stack.isEmpty()) {
return false;
}
return true;
}
}
1047. 删除字符串中的所有相邻重复项
1.自己的写的,但是效率不好。时间140 ms,内存46.6 MB。
class Solution {
public String removeDuplicates(String s) {
Deque<Character> deque = new LinkedList<Character>();
char ch;
for (int i = 0; i<s.length() ;i++) {
ch = s.charAt(i);
if (!deque.isEmpty() && ch == deque.peek()) {
deque.pop();
} else {
deque.push(ch);
}
}
s = "";
while (!deque.isEmpty()) {
s = deque.pop() + s;
}
return s;
}
}
150. 逆波兰表达式求值
class Solution {
public int evalRPN(String[] tokens) {
Deque<Integer> deque = new LinkedList<Integer>();
for (int i = 0 ; i<tokens.length; i++) {
String token = tokens[i];
if ("+".equals(token)) {
deque.push(deque.pop() + deque.pop());
} else if ("-".equals(token)) {
int num1 = deque.pop();
int num2 = deque.pop();
deque.push(num2 - num1);
} else if ("*".equals(token)) {
deque.push(deque.pop() * deque.pop());
} else if ("/".equals(token)) {
int num1 = deque.pop();
int num2 = deque.pop();
deque.push(num2 / num1);
} else {
deque.push(Integer.valueOf(token));
}
}
return deque.pop();
}
}