LeetCode刷题--(数组)

20. 有效的括号

注意:局部变量使用的是基本类型。

 public static boolean isValid(String s) {
        //建立一个配对字典
        Map<Character,Character> map =new HashMap<Character,Character>();
        map.put('(',')');
        map.put('[',']');
        map.put('{','}');
        Stack<Character> stack =new Stack<Character>();

        for(int i=0;i<s.length();i++){
            char  ch = s.charAt(i);
            if(ch==')' || ch==']'||ch=='}'){

                if(stack.empty()||map.get(stack.peek())!=ch){
                    return false;
                }else{
                    stack.pop();
                }
            }else{
                stack.push(ch);
            }
        }
        return stack.isEmpty();
    }

25.用队列实现栈

注意:在pop和top操作之后,需要交换一下引用,以便于下次的操作。

class MyStack {
    private Queue<Integer> queue;
    private Queue<Integer> help;

    /** Initialize your data structure here. */
    public MyStack() {
        queue=new LinkedList<Integer>();
        help =new LinkedList<Integer>();
    }
    
    /** Push element x onto stack. */
    public void push(int x) {
        queue.add(x);
        
    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        if(queue.isEmpty()){
            throw new RuntimeException("栈空了");
        }
        while(queue.size()>1){
            help.add(queue.poll());
        }
        int res =queue.poll();
        swap();
        return res;
    }
    
    /** Get the top element. */
    public int top() {
           if(queue.isEmpty()){
            throw new RuntimeException("栈空了");
        }
        while(queue.size()>1){
            help.add(queue.poll());
        }
        int res =queue.poll();
        help.add(res);
        swap();
        return res; 
        
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
        return queue.isEmpty();
        
    }
    public void swap(){
        Queue<Integer> temp =queue;
        queue=help;
        help=temp;
    }
}

你可能感兴趣的:(LeetCode刷题笔记)