代码训练day10栈与队列

1.用栈实现队列

从peek和pop共同特性抽取的方法

class MyQueue {

    // 两个输入输出栈 队列先入先出,栈后入先出,需要输出栈将结果倒序。

    Stack stackIn;

    Stack stackOut;



    public MyQueue() {

        stackIn = new Stack<>();

        stackOut = new Stack<>();



    }

   

    public void push(int x) {// 放入

        stackIn.push(x);

    }

   

    public int pop() { // 首部移除

        dumpstackIn();

        return stackOut.pop();

    }

   

    public int peek(){ // 返回队列首部元素

        dumpstackIn();

        return stackOut.peek();

    }

   

    public boolean empty(){

        return stackIn.isEmpty() && stackOut.isEmpty();

    }



    private void dumpstackIn(){// 移出in的数据使之倒序。从peek和pop共同特性抽取的方法

        if (!stackOut.isEmpty()) return; // stackout不为空

        while (!stackIn.isEmpty())  { // in全部弹出

            stackOut.push(stackIn.pop());

        }

    }

}

2.用队列实现栈

class MyStack {
    // q1存放的顺序为出栈的顺序,实现方式为用q2作为辅助队列。
    // push的时候弹出q1所有,加入当前元素,然后q2全部返回到q1
    Queue q1 = new ArrayDeque<>();
    Queue q2 = new ArrayDeque<>();
    public MyStack() {

         q1 = new ArrayDeque<>();
         q2 = new ArrayDeque<>();

    }
    
    public void push(int x) {
        while (q1.size() > 0) {
            q2.add(q1.poll());
        }
        q1.add(x);
        while (q2.size() > 0) {
            q1.add(q2.poll());
        }
    }
    
    public int pop() {
        return q1.poll();
    }
    
    public int top() {
        return q1.peek();
    }
    
    public boolean empty() {
        return q1.isEmpty();
    }
}

3.有效的括号

class Solution {
    // 栈顶消消乐 c == ')' && !stack.isEmpty() && stack.peek() == '('
    public boolean isValid(String s) {
        Stack stack = new Stack<>();
        for (char c : s.toCharArray()) {
            if (c == ')' && !stack.isEmpty() && stack.peek() == '(')
                stack.pop();
            else if (c == '}' && !stack.isEmpty() && stack.peek() == '{' )
                stack.pop();
            else if (c == ']' && !stack.isEmpty() && stack.peek() == '[')
                stack.pop();
            else
                stack.push(c);// 不匹配就放入
        }
        return stack.isEmpty();
    }
}

4.删除字符串中所有的相邻重复项

class Solution {
    // 栈顶消消乐
    public String removeDuplicates(String s) {
        Deque deque = new ArrayDeque<>();
        char ch;
        for (int i = 0; i < s.length(); i++) {
            ch = s.charAt(i);
            if (deque.isEmpty() || deque.peek() != ch) {// 为空或栈顶元素不等于当前入栈元素
                deque.push(ch);
            } else {
                deque.pop();
            }
        }
        String str = new String();
        while (!deque.isEmpty()) {
            str = deque.pop() + str;
        }
        return str;
    }
}

你可能感兴趣的:(代码随想录刷题,java,开发语言)