20.有效的括号
class Solution {
public boolean isValid(String s) {
if(s.length()%2 == 1) {
return false;
}
Deque<Character> q = new LinkedList<>();
for(int i = 0; i < s.length(); ++i) {
if(s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{') {
q.offerLast(s.charAt(i));
}else {
if(q.isEmpty()) {
return false;
}else if(q.peekLast() == '(' && s.charAt(i) == ')') {
q.pollLast();
}else if(q.peekLast() == '[' && s.charAt(i) == ']'){
q.pollLast();
}else if(q.peekLast() == '{' && s.charAt(i) == '}') {
q.pollLast();
}else {
return false;
}
}
}
return q.isEmpty();
}
}
1047.删除字符串中的所有相邻重复项
题目链接:1047. 删除字符串中的所有相邻重复项 - 力扣(LeetCode)
class Solution {
public String removeDuplicates(String s) {
Deque<Character> dq = new LinkedList<>();
for(int i = 0; i < s.length(); ++i) {
if(dq.isEmpty() || s.charAt(i) != dq.peekLast()) {
dq.offerLast(s.charAt(i));
}else {
dq.pollLast();
}
}
StringBuffer sbuf = new StringBuffer();
while (!dq.isEmpty()) {
sbuf.append(dq.pollFirst());
}
return sbuf.toString();
}
}
150.逆波兰表达式求值
题目链接:150. 逆波兰表达式求值 - 力扣(LeetCode)
class Solution {
public int evalRPN(String[] tokens) {
Deque<Integer> dq = new LinkedList<>();
char ch;
for(int i = 0; i < tokens.length; ++i) {
if(tokens[i].length() > 1) {
ch = tokens[i].charAt(1);
} else {
ch = tokens[i].charAt(0);
}
if(ch >= '0' && ch <= '9') {
dq.offerLast(Integer.parseInt(tokens[i]));
}else {
int a = dq.pollLast(), b = dq.pollLast();
switch (ch) {
case '+':
dq.offerLast(a+b);
break;
case '-':
dq.offerLast(b-a);
break;
case '*':
dq.offerLast(b*a);
break;
case '/':
dq.offerLast(b/a);
break;
default:
break;
}
}
}
return dq.pollLast();
}
}