堆栈

107 阅读1分钟

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

//leetcode 155 思路:用另一个栈存放最小值

class MinStack {    

    Deque<Integer> stack ;    
    Deque<Integer> min_stack ;   
 
    /** initialize your data structure here. */  
  
    public MinStack() {        
        stack = new LinkedList<Integer>();        
        min_stack = new LinkedList<Integer>();        
        min_stack.addFirst(Integer.MAX_VALUE);    
    }        

    public void push(int val) {        
        stack.addFirst(val);        
        int min = min_stack.peekFirst();        
        if(val<min){            
        min_stack.addFirst(val);        
        }else{            
            min_stack.addFirst(min);        
        }    
    }       
     
    public void pop() {        
        stack.removeFirst();        
        min_stack.removeFirst();    
    }    
    
    public int top() {        
        return stack.peekFirst();    
    }   
     
    public int getMin() {        
        return min_stack.peekFirst();    
    }
}

2. 逆波兰表达式求值

// leetcode 150
class Solution {    
    public int evalRPN(String[] tokens) {        
        String[] arr = new String[]{"+","-","*","/"};        
        List<String> operations = Arrays.asList(arr);        
        Deque<Integer> stack = new LinkedList<Integer>();        
        int c = 0;        
        for(String str: tokens){            
            if(operations.contains(str)){                
                int a = stack.removeFirst();                
                int b = stack.removeFirst();                                
                if(str.equals("+")){                    
                    c = b + a;                
                }else if(str.equals("-")){                    
                    c = b - a;                
                }else if(str.equals("*")){                    
                    c = b * a;                
                }else if(str.equals("/")){                    
                    c = b / a;                
                }                
                stack.addFirst(c);             
            }else{                
                stack.addFirst(Integer.parseInt(str));             
            }        
        }        
        return stack.peekFirst();    
    }
}

3. 字符串解码

// leetcode 394
class Solution {    public String decodeString(String s) {        int length = s.length();        Deque<String> stack = new LinkedList<String>();        int i = 0;        while(i<length){             char c = s.charAt(i);            // 从栈中弹出元素开始拼接            if(c==']'){                String temp = stack.pollFirst();                String joint_str = "";                do{                     joint_str = temp + joint_str;                    temp = stack.pollFirst();                }while(!temp.equals("["));                int num = Integer.parseInt(stack.pollFirst());                String temp_result = "";                for(int j=0;j<num;j++){                    temp_result += joint_str;                }                stack.offerFirst(temp_result);                i++;            }else if(Character.isDigit(c)){                 //number                String str_value = String.valueOf(c);                String joint_str = "";                do{                    joint_str += str_value;                    i += 1;                    c = s.charAt(i);                    str_value = String.valueOf(c);                }while(!str_value.equals("["));                stack.offerFirst(joint_str);             }else{                String stack_value = String.valueOf(c);                stack.offerFirst(stack_value);                 i++;                           }        }                String result = "";        String poll_value = stack.pollFirst();        do{            result = poll_value + result;            poll_value = stack.pollFirst();        }while(poll_value!=null);        return result;    }}

4. 克隆图

// leetcode 133
//方法一:广度优先遍历
class Solution {
    public Node cloneGraph(Node node) {
        if(node==null){
            return node;
        }
        Map<Node,Node> map = new HashMap<>();
        map.put(node, new Node(node.val, new ArrayList<Node>()));

        Queue<Node> queue = new LinkedList<>();
        queue.offer(node);
        while(!queue.isEmpty()){
            Node temp_node = queue.poll();
            for(Node neighbor : temp_node.neighbors){
                if(map.get(neighbor)==null){
                    map.put(neighbor, new Node(neighbor.val, new ArrayList<Node>()));
                    queue.offer(neighbor);
                }
                map.get(temp_node).neighbors.add(map.get(neighbor));
            }

        }
        return map.get(node);
    }
}
//方法二:深度优先遍历
class Solution {
    Map<Node,Node> map = new HashMap<>();
    public Node cloneGraph(Node node) {
        if(node == null){
            return null;
        }
        if(map.get(node)!=null){
            return map.get(node);
        }
        Node cloneNode = new Node(node.val, new ArrayList<Node>());
        map.put(node, cloneNode);
        for(Node neighbor:node.neighbors){
            cloneNode.neighbors.add(cloneGraph(neighbor));
        }
        return map.get(node);
    }
}

5. 岛屿数量

# leetcode 200
# 方法一:深度优先
class Solution {    public int numIslands(char[][] grid) {        if(grid==null || grid.length==0){            return 0;        }        int result = 0;        int row_len = grid.length;        int col_len = grid[0].length;        for(int row=0;row<row_len;row++){            for(int col=0;col<col_len;col++){                if(grid[row][col] == '1'){                    result += 1;                    dfs(grid,row,col);                }            }        }        return result;    }    public void dfs(char[][] grid, int row, int col){        int row_len = grid.length;        int col_len = grid[0].length;        if(row<0 || row>=row_len || col<0 ||col>=col_len || grid[row][col]=='0'){            return;        }        grid[row][col] = '0';        dfs(grid, row-1, col);        dfs(grid, row+1, col);        dfs(grid, row, col-1);        dfs(grid, row, col+1);    }}

# 方法二:广度优先class Solution {    public int numIslands(char[][] grid) {        if(grid==null || grid.length==0){            return 0;        }        int result = 0;        int row_len = grid.length;        int col_len = grid[0].length;               for(int row=0;row<row_len;row++){            for(int col=0;col<col_len;col++){                if(grid[row][col] == '1'){                    result += 1;                    grid[row][col] = '0';                    Queue<Integer> queue = new LinkedList<>();                    queue.offer(row*col_len+col);                    while(!queue.isEmpty()){                        int value = queue.poll();                        int r = value/col_len;                        int c = value%col_len;                        if(r-1>=0 && grid[r-1][c]=='1'){                            grid[r-1][c] = '0';                            queue.offer(col_len*(r-1)+c);                        }                        if(r+1<row_len && grid[r+1][c]=='1'){                            grid[r+1][c] = '0';                            queue.offer(col_len*(r+1)+c);                        }                        if(c-1>=0 && grid[r][c-1]=='1'){                            grid[r][c-1] = '0';                            queue.offer(col_len*r+c-1);                        }                        if(c+1<col_len && grid[r][c+1]=='1'){                            grid[r][c+1] = '0';                            queue.offer(col_len*r+c+1);                        }                    }                }            }        }        return result;    }}