LeetCode 323.用栈实现队列
题目描述
请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):
实现 MyQueue 类:
void push(int x)将元素 x 推到队列的末尾int pop()从队列的开头移除并返回元素int peek()返回队列开头的元素boolean empty()如果队列为空,返回true;否则,返回false
说明:
- 你 只能 使用标准的栈操作 —— 也就是只有 
push to top,peek/pop from top,size, 和is empty操作是合法的。 - 你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
 
示例
输入:
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 1, 1, false]解释:
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false
题目链接
https://leetcode.cn/problems/implement-queue-using-stacks/description/
解题思路
一个栈用来模拟队列,即栈顶就是队首。
另外一个栈用来辅助
class MyQueue {
    // 辅助队列
    Stack<Integer> stackIn;
    // 模拟队列, 栈顶永远就是队首
    Stack<Integer> stackOut;
    public MyQueue() {
        stackIn = new Stack<>();
        stackOut = new Stack<>();
    }
  
    public void push(int x) {
        // 输出栈缓存到输入栈
        while (!stackOut.isEmpty()) {
            stackIn.push(stackOut.pop());
        }
        // 插入新元素
        stackOut.push(x);
        // 输入栈内容转回输出栈
        while (!stackIn.isEmpty()) {
            stackOut.push(stackIn.pop());
        }
    }
  
    public int pop() {
        return stackOut.pop();
    }
  
    public int peek() {
        return stackOut.peek();
  
    }
  
    public boolean empty() {
        return stackOut.isEmpty();
    }
}
/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue obj = new MyQueue();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.peek();
 * boolean param_4 = obj.empty();
 */
LeetCode 225. 用队列实现栈
题目描述
请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push、top、pop 和 empty)。
实现 MyStack 类:
void push(int x)将元素 x 压入栈顶。int pop()移除并返回栈顶元素。int top()返回栈顶元素。boolean empty()如果栈是空的,返回true;否则,返回false。
注意:
- 你只能使用队列的标准操作 —— 也就是 
push to back、peek/pop from front、size和is empty这些操作。 - 你所使用的语言也许不支持队列。 你可以使用 list (列表)或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
 
示例
输入:
["MyStack", "push", "push", "top", "pop", "empty"]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 2, 2, false]解释:
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // 返回 2
myStack.pop(); // 返回 2
myStack.empty(); // 返回 False
题目链接
https://leetcode.cn/problems/implement-stack-using-queues/description/
解题思路
一个队列模拟栈,保证队首即栈顶
注意:不要用 Deque,它的 push方法默认是插入队首。用了就和栈没区别,不能更好理解栈和队列。非要用建议使用 addLast或 offerLast
// 11m26s
class MyStack {
    // 辅助队列, 长期为空
    Queue<Integer> queue;
    // 模拟栈, 队首就是栈顶
    Queue<Integer> stack;
    public MyStack() {
        queue = new LinkedList<>();
        stack = new LinkedList<>();
    }
  
    public void push(int x) {
        // 暂存队列
        while (!stack.isEmpty()) {
            queue.offer(stack.poll());
        }
        stack.offer(x);
        while (!queue.isEmpty()) {
            stack.offer(queue.poll());
        }
    }
  
    public int pop() {
        return stack.poll();
    }
  
    public int top() {
        return stack.peek();
    }
  
    public boolean empty() {
        return stack.isEmpty();
    }
}
/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack obj = new MyStack();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.top();
 * boolean param_4 = obj.empty();
 */
LeetCode 20. 有效的括号
题目描述
给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
 - 左括号必须以正确的顺序闭合。
 - 每个右括号都有一个对应的相同类型的左括号。
 
示例
**输入:**s = "()[]{}"
**输出:**true
题目链接
https://leetcode.cn/problems/valid-parentheses/description/
解题思路
用栈来匹配。栈顶需要和当前符号匹配。否则失败。
使用 HashMap来提高匹配效率
class Solution {
    public boolean isValid(String s) {
        // 奇数个,一定无法匹配
        if (s.length() % 2 == 1) {
            return false;
        }
        Map<Character, Character> match = new HashMap<>() {
            {
                put(')', '(');
                put(']', '[');
                put('}', '{');
            }
        };
        Stack<Character> stack = new Stack<>();
        for (char ch : s.toCharArray()) {
            if (match.containsKey(ch)) {
                if (stack.isEmpty() || stack.peek() != match.get(ch)) {
                    return false;
                }
                stack.pop();
            } else {
                stack.push(ch);
            }
        }
        return stack.isEmpty();
    }
}
LeetCode 1047. 删除字符串中的所有相邻重复项
题目描述
给出由小写字母组成的字符串 s,重复项删除操作会选择两个相邻且相同的字母,并删除它们。
在 s 上反复执行重复项删除操作,直到无法继续删除。
在完成所有重复项删除操作后返回最终的字符串。答案保证唯一。
示例
输入:"abbaca"
输出:"ca"
解释:
例如,在 "abbaca" 中,我们可以删除 "bb" 由于两字母相邻且相同,这是此时唯一可以执行删除操作的重复项。之后我们得到字符串 "aaca",其中又只有 "aa" 可以执行重复项删除操作,所以最后的字符串为 "ca"。
题目链接
https://leetcode.cn/problems/remove-all-adjacent-duplicates-in-string/description/
解题思路
用栈来进行匹配。类似括号匹配。然后输出栈的内容。
// 5m51s
class Solution {
    public String removeDuplicates(String s) {
        Stack<Character> stack = new Stack<>();
        for (char ch : s.toCharArray()) {
            if (!stack.isEmpty() && ch == stack.peek()) {
                stack.pop();
            } else {
                stack.push(ch);
            }
        }
        StringBuilder ans = new StringBuilder();
        while (!stack.isEmpty()) {
            ans.append(stack.pop());
        }
        return ans.reverse().toString();
    }
}
双指针法。快指针进行搜索。当快指针比慢指针前一个相同时则删除。
class Solution {
    public String removeDuplicates(String s) {
        char[] ch = s.toCharArray();
        int slow = 0, fast = 0;
        while (fast < ch.length) {
            ch[slow] = ch[fast];
            if (slow > 0 && ch[fast] == ch[slow - 1]) {
                slow--;
            } else {
                slow++;
            }
            fast++;
        }
        return new String(ch, 0, slow);
    }
}
                
            
评论