栈和队列
文章目录
一、栈
1、简单的栈运用
20. 有效的括号
给定一个字符串,只包含(,[,{,),],}, 判定字符串中的括号匹配是否合法。
- 如"()”,“()[{"是合法的
- 如“(]","([)]" 是非法的
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for(int i = 0;i < s.length();i++) {
char t = s.charAt(i);
if(t == '[' || t == '{' || t == '(' ) {
stack.push(t);
}
else {
if(stack.isEmpty()) return false;
if(t == ')') {
if(stack.isEmpty()) return false;
if(stack.peek() == '(') stack.pop();
else return false;
}
if(t == '}') {
if(stack.peek() == '{') stack.pop();
else return false;
}
if(t == ']') {
if(stack.peek() == '[') stack.pop();
else return false;
}
}
}
if(!stack.isEmpty()) return false;
return true;
}
}
拓展:
Evaluate Reverse Polish Notation
Simplify Path
2、栈和递归的紧密关系
2.1、递归算法
二叉树中的算法
前序、中序和后序遍历
- Binary Tree Preorder Traversal
-
Binary Tree Inorder Traversal
-
Binary Tree Postorder Traversal
2.2、使用栈模拟系统栈,写出非递归程序
LeetCode 144. 二叉树前序遍历
public class Solution144 {
// Definition for a binary tree node.
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x; }
}
private class Command{
String s; // go, print
TreeNode node;
Command(String s, TreeNode node){
this.s = s;
this.node = node;
}
};
public List<Integer> preorderTraversal(TreeNode root) {
ArrayList<Integer> res = new ArrayList<Integer>();
if(root == null)
return res;
Stack<Command> stack = new Stack<Command>();
stack.push(new Command("go", root));
while(!stack.empty()){
Command command = stack.pop();
if(command.s.equals("print"))
res.add(command.node.val);
else{
assert command.s.equals("go");
if(command.node.right != null)
stack.push(new Command("go",command.node.right));
if(command.node.left != null)
stack.push(new Command("go",command.node.left));
stack.push(new Command("print", command.node));
}
}
return res;
}
}
public class Solution1 {
public List<Integer> preorderTraversal(TreeNode root) {
ArrayList<Integer> res = new ArrayList