代码随想录算法训练营Day10

栈与队列

用栈实现队列

class MyQueue {  
    /*  
    一个栈是输入栈,另一个栈是输出栈  
    当pop时,如果输入栈有元素,则将其全部push进输出栈,再pop  
    */    
    Stack<Integer> InPutStack;  //注意在这里声明!
    Stack<Integer> OutPutStack;  
    public MyQueue() {  //构造函数初始化
        InPutStack = new Stack<>();  
        OutPutStack = new Stack<>();  
    }  
  
    public void push(int x) {  
        InPutStack.push(x);  
    }  
  
    public int pop() {  
        if(OutPutStack.empty()){  
            while(!InPutStack.empty()){  
                OutPutStack.push(InPutStack.pop());  
            }  
            return OutPutStack.pop();  
        }else{  
            return OutPutStack.pop();  
        }  
    }  
  
    public int peek() {  
        if(OutPutStack.empty()){  
            while(!InPutStack.empty()){  
                OutPutStack.push(InPutStack.pop());  
            }  
            return OutPutStack.peek();  
        }else{  
            return OutPutStack.peek();  
        }  
    }  
  
    public boolean empty() {  
        if(OutPutStack.empty()&&InPutStack.empty()){  
            return true;  
        }else{  
            return false;  
        }  
    }  
}  
  
/**  
 * 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(); */

队列实现栈

前面元素弹出后再加回队尾

class MyStack {  
    Queue<Integer> queue;  
  
    public MyStack() {  
        queue = new LinkedList<>();  
    }  
  
    // 将元素压入栈顶  
    public void push(int x) {  
        queue.add(x);  
    }  
  
    // 移除并返回栈顶元素  
    public int pop() {  
        int size = queue.size();  
        for (int i = 0; i < size - 1; i++) {  
            queue.add(queue.poll());  
        }  
        return queue.poll();  
    }  
  
    // 返回栈顶元素但不移除  
    public int top() {  
        int size = queue.size();  
        int result = 0;  
        for (int i = 0; i < size; i++) {  
            result = queue.poll(); // 获取当前队头元素  
            queue.add(result); // 将元素重新加入队列  
        }  
        return result;  
    }  
  
    // 判断栈是否为空  
    public boolean empty() {  
        return queue.isEmpty();  
    }  
}

括号匹配

  1. 左右括号不匹配
  2. 遍历到右括号时,栈为空
  3. 字符串遍历结束后,栈不为空(有没有被匹配的左括号)
class Solution {  
    // 遇到左括号就入栈,遇到右括号就出栈并检查是否匹配  
    public boolean isValid(String s) {  
        // 使用栈来存储左括号  
        Stack<Character> stack = new Stack<>();  
  
        // 遍历字符串中的每个字符  
        for (char c : s.toCharArray()) {  
            // 如果是左括号,则入栈  
            if (c == '(' || c == '{' || c == '[') {  
                stack.push(c);  
            } else {  
                // 如果是右括号,先检查栈是否为空  
                if (stack.isEmpty()) {  
                    return false; // 栈为空说明没有匹配的左括号  
                }  
  
                // 弹出栈顶元素并检查是否匹配  
                char top = stack.pop();  
                if ((top == '(' && c != ')') ||  
                        (top == '{' && c != '}') ||  
                        (top == '[' && c != ']')) {  
                    return false; // 不匹配直接返回 false                }  
            }  
        }  
  
        // 最后检查栈是否为空,如果为空说明完全匹配,否则说明有多余的左括号  
        return stack.isEmpty();  
    }  
}

删除相邻重复项

class Solution {
	public String removeDuplicates(String s) {
		//删除相邻的重复项,用栈解决
		char[] arr = s.toCharArray();
		Stack<Character> stack = new Stack<Character>();
		for(char c : arr){//这里的顺序影响结果
			if (!stack.isEmpty() && stack.peek() == c) {
				stack.pop();
			} else {
				// 否则将当前字符入栈
				stack.push(c);
			}
		}
		StringBuilder result = new StringBuilder();
		for (char c : stack) {
			result.append(c);
		}
		return result.toString();
	}
}
posted @ 2025-04-04 17:18  Anson_502  阅读(10)  评论(0)    收藏  举报