先进后出 LinkedList image.png 有最近一直性的东西用栈 比如括号匹配


20. 括号匹配

image.png

  1. class Solution {
  2. public boolean isValid(String s) {
  3. LinkedList<Character> stack = new LinkedList();
  4. char[] chars = s.toCharArray();
  5. for (char c : chars) {
  6. if (c == '(') {
  7. stack.push(')');
  8. } else if (c == '{') {
  9. stack.push('}');
  10. } else if (c == '[') {
  11. stack.push(']');
  12. }
  13. if (c == ')' || c == '}' || c == ']') {
  14. if(stack.peek() == null ||stack.pop() != c) return false;
  15. }
  16. }
  17. return stack.peek() == null ;
  18. }
  19. }

155. 最小栈

image.png

  1. class MinStack {
  2. private Node top;
  3. /** initialize your data structure here. */
  4. public MinStack() {
  5. }
  6. public void push(int val) {
  7. if (top == null)
  8. top = new Node(val, val);
  9. else {
  10. top = new Node(val, Math.min(val, top.min), top);
  11. }
  12. }
  13. public void pop() {
  14. top = top.pre;
  15. }
  16. public int top() {
  17. return top.val;
  18. }
  19. public int getMin() {
  20. return top.min;
  21. }
  22. private class Node {
  23. int val;
  24. int min;
  25. Node pre;
  26. public Node (int val, int min, Node pre) {
  27. this(val,min);
  28. this.pre = pre;
  29. }
  30. public Node (int val, int min) {
  31. this.val = val;
  32. this.min = min;
  33. }
  34. }
  35. }