当前位置:网站首页>Sword finger offer 09 Implementing queues with two stacks

Sword finger offer 09 Implementing queues with two stacks

2022-07-05 05:28:00 ThE wAlkIng D

Title Description

 Given a string s , Please find out that there are no duplicate characters in it Longest substrings The length of .

Problem analysis ( This question uses a sliding window +HashMap)

1. First define two stacks s1,s2,s1 The top of the stack is the tail of the team ,s2 The top of the stack as a team cast
2. To delete, first judge s2 Is it empty If it's not empty , Popping the top element of the stack is the header element If it is empty , take s1 All elements pop into the stack s2
3.s2 Empty return -1, If it is not empty, return the top of stack element

Code instance

class CQueue {
    
    Stack<Integer> s1 = new Stack<>();  // s1 The top of the stack is the tail of the team , The newly added element is at the top of the stack 
    Stack<Integer> s2 = new Stack<>();  // s2 At the top of the stack is the head of the team 
    public CQueue() {
    
    }
    
    public void appendTail(int value) {
    
        s1.push(value); //  Push to stack s1
    }
    
    public int deleteHead() {
    
        if(!s2.isEmpty()) {
     //  if s2 Not empty , Directly pop up the top element of the stack, that is, the team head element 
            return s2.pop();
        }
        // s2 It's empty , take s1 All elements pop up , Stack to s2
        while(!s1.isEmpty()) {
    
            s2.push(s1.pop());
        }
        return s2.isEmpty() ? -1 : s2.pop(); // s2 It's empty , return -1;s2 If it is not empty, return the top of stack element 
    }
}



/** * Your CQueue object will be instantiated and called as such: * CQueue obj = new CQueue(); * obj.appendTail(value); * int param_2 = obj.deleteHead(); */
    }
}
原网站

版权声明
本文为[ThE wAlkIng D]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207050525449739.html