java 中栈的使用
相比于Stack
,更应该使用Deque
双端队列(先进后出)
- 实现
- ArrayDeque:可变数组来实现的,无容量限制,可自动扩容。ArrayDeque作为栈效率要高于 Stack;作为队列效率高于LinkedList
- LinkedList
- 函数
- push()
- pop()
- isEmpty()
- peek()
leetcode 20
题目链接
括号匹配问题
思路:
- 我的思路:
- 遇到
(
、[
、{
符号,压入栈中 - 遇到
)
、]
、}
,将栈中元素弹出(前提stack
非空),判断两者是否匹配 - 注意
return true
条件:遍历完字符串后,stack为空!
- 遇到
- 另一种思路:
- 三种不匹配的情况:
- 字符串里左方向的括号多余了 ,所以不匹配
- 括号没有多余,但是 括号的类型没有匹配上
- 字符串里右方向的括号多余了,所以不匹配
- 代码直接遇到
(
,将)
压入栈 - 遇到
)
,将栈顶元素弹出,比较是否相等
- 三种不匹配的情况:
- note:
char
类型——<Character>
我的思路代码
class Solution {
public boolean isValid(String s) {
if (s.length() % 2 != 0)
return false;
Stack<Character> stack = new Stack<>();
char[] ch = s.toCharArray();
for (char x : ch) {
if (x == '{' || x == '[' || x == '(')
stack.push(x);
else {
if (!stack.empty()) {
char temp = stack.pop();
if (!match(temp, x))
return false;
}
else
return false;
}
}
if (stack.empty())
return true;
else
return false;
}
public boolean match(char a, char b) {
if (a == '(' && b == ')')
return true;
else if (a == '[' && b == ']')
return true;
else if (a == '{' && b == '}')
return true;
else
return false;
}
}
leetcode 1047
题目链接
删除相邻重复项
思路:
- 我的思路:
- like leetcode 20括号匹配
- 用堆栈解决
- 最后返回结果时,可以利用java字符串
+
功能
String str = "";
//剩余的元素即为不重复的元素
while (!stack.isEmpty()) {
str = stack.pop() + str;
}
- 另一种思路:
- 双指针
- 快慢指针,直接覆盖重复
代码
class Solution {
public String removeDuplicates(String s) {
Deque<Character> stack = new ArrayDeque<>();
for (int i = 0; i < s.length(); ++i) {
char x = s.charAt(i);
if (stack.isEmpty())
stack.push(x);
else {
char temp = stack.peek();
if (temp == x)
stack.pop();
else
stack.push(x);
}
}
int len = stack.size();
char[] ch = new char[len];
for (int i = len - 1; i >= 0; --i) {
ch[i] = stack.pop();
}
return String.valueOf(ch);
}
}
leetcode 150
题目链接
逆波兰表达式(reverse Polish Notation):后缀表达式,二叉树后序遍历
思路:
- like leetcode 20、leetcode 1047;还是配对的问题
- 每次遇到运算符:弹出2个数,求结果,再压入栈
Integer.parseInt()
或者Integer.valueOf()
可以将String
转换成int
class Solution {
public int evalRPN(String[] tokens) {
Deque<Integer> stack = new ArrayDeque<>();
for (int i = 0; i < tokens.length; ++i) {
if (isNumber(tokens[i])) {
int x = Integer.parseInt(tokens[i]); //change String into int
stack.push(x);
}
else {
int b = stack.pop();
int a = stack.pop();
int res = 0;
//这里最好用.equals()进行比较
switch (tokens[i]) {
case "+": res = a + b; break;
case "-": res = a - b; break;
case "*": res = a * b; break;
case "/": res = a / b; break;
default: res = 0;
}
stack.push(res);
}
}
return stack.pop();
}
public boolean isNumber(String s) {
char[] ch = s.toCharArray();
if (ch[0] <= '9' && ch[0] >= '0')
return true;
else if (ch[0] == '-' && ch.length > 1 && ch[1] <= '9' && ch[1] >= '0')
return true;
else
return false;
}
}