20. 有效的括号
1.题目描述
2.适用场景
3.做题思路
charAt(i)是String类中的一个方法,用于返回字符串中索引为i位置的字符。
Deque<Character>
表示一个双端队列(Deque)类型,该队列中存储的元素类型是Character
,即字符类型
在队列中放右括号,对比
4.代码实现
class Solution {
public boolean isValid(String s) {
Deque <Character> deque = new LinkedList <>();
char ch;
for(int i = 0; i<s.length(); i++){
ch = s.charAt(i);
if(ch == '('){
deque.push(')');}
else if(ch == '['){
deque.push(']');}
else if(ch == '{'){
deque.push('}');}
else if(deque.isEmpty() || deque.peek() != ch){
return false;}
else{
deque.pop();}
}
return deque.isEmpty();
}
}
5.总结
1047. 删除字符串中的所有相邻重复项
1.题目描述
2.适用场景
- 时间复杂度: O(n)
- 空间复杂度: O(n)
3.做题思路
消消乐
4.代码实现
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;
}
}
5.总结
空字符串定义是“”,不是‘’
堆栈
150. 逆波兰表达式求值
1.题目描述
2.适用场景
- 时间复杂度: O(n)
- 空间复杂度: O(n)
3.做题思路
也是两个数的消消乐
4.代码实现
class Solution {
public int evalRPN(String[] tokens) {
Deque<Integer> stack = new LinkedList();
for (String s : tokens) {
if ("+".equals(s)) {
stack.push(stack.pop() + stack.pop());
} else if ("-".equals(s)) {
stack.push(-stack.pop() + stack.pop());
} else if ("*".equals(s)) {
stack.push(stack.pop() * stack.pop());
} else if ("/".equals(s)) {
int temp1 = stack.pop();
int temp2 = stack.pop();
stack.push(temp2 / temp1);
} else {
stack.push(Integer.valueOf(s));
}
}
return stack.pop();
}
}
5.总结
.valueOf(s)
方法将字符串s
转换为对应的整数形式