代码随想录1.31

文章目录

    • 232 用栈实现队列
    • 225. 用队列实现栈
    • 20. 有效的括号

232 用栈实现队列

**c++语法:
定义栈:stack stIn;
往栈里输入元素:stIn.push(x);
检测栈中是否为空::stIn.empty()
返回栈顶,但不删除成员:stIn.top()
移除栈顶元素:stIn.pop()
返回栈内元素的大小:stIn.size()

class MyQueue {
public:
    stack<int> stIn;
    stack<int> stOut;
    MyQueue() {
        
    }
    
    void push(int x) {
        stIn.push(x);
    }
    
    int pop() {
        if(stOut.empty()){
            while(!stIn.empty()){
                stOut.push(stIn.top());//返回栈顶,但不删除成员:stIn.top()
                stIn.pop();//删除
            }
        }
        int res = stOut.top();
        stOut.pop();
        return res;
    }
    
    int peek() {
        //可以直接用上面写好的pop函数,再添加上删除掉的元素即可
        int res = this->pop();//用this指针,代表通过 this 访问成员变量和成员函数
        stOut.push(res);
        return res;
    }
    
    bool empty() {
        return stIn.empty() && stOut.empty();
    }
};

/**
 * 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();
 * bool param_4 = obj->empty();
 */

225. 用队列实现栈

**c++语法:
定义栈:queue que1;
返回队列中的第一个元素,但不删除该元素:que1.front()

20. 有效的括号

括号匹配是使用栈解决的经典问题
几种情况:

  1. 如果字符串总数长度为奇数那一定不符合
  2. 左方向括号多余
  3. 右方向括号多余
  4. 括号类型匹配不上

遍历输入的字符串,如果某位置是(,入栈),是[,入栈],是{,入栈},然后出战

class Solution {
public:
    bool isValid(string s) {
        if (s.size() % 2 != 0) return false; // 如果s的长度为奇数,一定不符合要求
        stack<char> st;
        for (int i = 0; i < s.size(); i++) {
            if (s[i] == '(') st.push(')');
            else if (s[i] == '{') st.push('}');
            else if (s[i] == '[') st.push(']');
            // 第三种情况:遍历字符串匹配的过程中,栈已经为空了,没有匹配的字符了,说明右括号没有找到对应的左括号 return false
            // 第二种情况:遍历字符串匹配的过程中,发现栈里没有我们要匹配的字符。所以return false
            else if (st.empty() || st.top() != s[i]) return false;//空字符串或不匹配
            else st.pop(); // st.top() 与 s[i]相等,栈弹出元素
        }
        // 第一种情况:此时我们已经遍历完了字符串,但是栈不为空,说明有相应的左括号没有右括号来匹配,所以return false,否则就return true
        return st.empty();
    }
};

你可能感兴趣的:(代码随想录跟练记录,数据结构,算法,c++,力扣,开发语言)