image.png

155. 最小栈

设计一个支持 pushpoptop 操作,并能在常数时间内检索到最小元素的栈。

  • push(x) —— 将元素 x 推入栈中。
  • pop() —— 删除栈顶的元素。
  • top() —— 获取栈顶元素。
  • getMin() —— 检索栈中的最小元素。


    示例:
    输入:
    [“MinStack”,”push”,”push”,”push”,”getMin”,”pop”,”top”,”getMin”]
    [[],[-2],[0],[-3],[],[],[],[]]

输出:
[null,null,null,null,-3,null,0,-2]

解释:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); —> 返回 -3.
minStack.pop();
minStack.top(); —> 返回 0.
minStack.getMin(); —> 返回 -2.

  1. class MinStack {
  2. Deque<Integer> Stack;
  3. Deque<Integer> minStack;
  4. /** initialize your data structure here. */
  5. public MinStack() {
  6. Stack=new LinkedList<Integer>();
  7. minStack=new LinkedList<Integer>();
  8. minStack.push(Integer.MAX_VALUE);
  9. }
  10. public void push(int x) {
  11. Stack.push(x);
  12. minStack.push(Math.min(x,minStack.peek()));
  13. }
  14. public void pop() {
  15. Stack.pop();
  16. minStack.pop();
  17. }
  18. public int top() {
  19. return Stack.peek();
  20. }
  21. public int getMin() {
  22. return minStack.peek();
  23. }
  24. }

76. 最小覆盖子串

给你一个字符串 s 、一个字符串 t 。返回 s 中涵盖 t 所有字符的最小子串。如果 s 中不存在涵盖 t 所有字符的子串,则返回空字符串 ""
注意:如果 s 中存在这样的子串,我们保证它是唯一的答案。

示例 1:
输入:s = “ADOBECODEBANC”, t = “ABC”
输出:“BANC”

示例 2:
输入:s = “a”, t = “a”
输出:“a”


提示:

  • 1 <= s.length, t.length <= 10
  • st 由英文字母组成
    1. class Solution {
    2. public String minWindow(String s, String t) {
    3. String res="";
    4. if (s.length() < t.length()) return res;
    5. int[] need = new int[128];
    6. char[] S=s.toCharArray();
    7. int cnt=0;
    8. // 利用数组来保存字符串 t 中每个元素出现的个数
    9. for (int i = 0; i < t.length(); i++) {
    10. need[t.charAt(i)]++;
    11. }
    12. for (int a : need) {
    13. if (a > 0) cnt ++;
    14. }
    15. for(int i=0,j=0,c=0;i<s.length();i++){
    16. // 刚好找到一个字符 计数器 ++
    17. if(need[S[i]]==1) c++;
    18. need[S[i]]--;// 不管是不是 t 中的元素,都 --
    19. while(c==cnt&&need[S[j]]<0) need[S[j++]]++;// 在找到完了元素之后才对指针 j 进行后移
    20. if(c==cnt){
    21. // 更新结果
    22. if(res==""||res.length()>i-j+1)
    23. res=s.substring(j,i+1);
    24. }
    25. }
    26. return res;
    27. }
    28. }