leetcode 栈与队列

leetcode 栈与队列

栈与队列

java中栈与队列的所有常用的实现方法

1.用栈实现队列

力扣题目链接

2.用队列实现栈

力扣题目链接

3.有效的括号

力扣题目链接

给定一个只包括 '('')''{''}''['']' 的字符串 s ,判断字符串是否有效。

有效字符串需满足:

  1. 左括号必须用相同类型的右括号闭合。
  2. 左括号必须以正确的顺序闭合。
  3. 每个右括号都有一个对应的相同类型的左括号。

示例 1:

1
2
输入:s = "()"
输出:true

示例 2:

1
2
输入:s = "()[]{}"
输出:true

示例 3:

1
2
输入:s = "(]"
输出:false

提示:

  • 1 <= s.length <= 104
  • s 仅由括号 '()[]{}' 组成
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
public boolean isValid(String s) {
Deque <Character> stack = new ArrayDeque<>();
for (int i = 0; i < s.length(); i++){
char 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 true;
} else {
return false;
}
}
}

4.删除字符串中的所有相邻重复项

力扣题目链接

给出由小写字母组成的字符串 S重复项删除操作会选择两个相邻且相同的字母,并删除它们。

在 S 上反复执行重复项删除操作,直到无法继续删除。

在完成所有重复项删除操作后返回最终的字符串。答案保证唯一。

示例:

1
2
3
4
输入:"abbaca"
输出:"ca"
解释:
例如,在 "abbaca" 中,我们可以删除 "bb" 由于两字母相邻且相同,这是此时唯一可以执行删除操作的重复项。之后我们得到字符串 "aaca",其中又只有 "aa" 可以执行重复项删除操作,所以最后的字符串为 "ca"。

提示:

  1. 1 <= S.length <= 20000
  2. S 仅由小写英文字母组成。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public String removeDuplicates(String s) {
ArrayDeque <Character> stack = new ArrayDeque<>();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (stack.isEmpty() || stack.peek()!=ch) {
stack.push(ch);
} else {
stack.pop();
}

}
String result = "";
while(!stack.isEmpty()) {
result = stack.pop()+result;
// result = stack.peek() + result;
// stack.pop();
}
return result;
}
}

5.逆波兰表达式求值

6.滑动窗口最大值

7.前k个高频元素

8.总结篇

作者

John Doe

发布于

2024-01-18

更新于

2025-02-28

许可协议

You need to set install_url to use ShareThis. Please set it in _config.yml.
You forgot to set the business or currency_code for Paypal. Please set it in _config.yml.

评论

You forgot to set the shortname for Disqus. Please set it in _config.yml.
You need to set client_id and slot_id to show this AD unit. Please set it in _config.yml.