11.1算法(栈和队列)

4.5左旋字符串

class Solution {
public:
    string dynamicPassword(string password, int target) {
        reverse(password.begin(),password.begin()+target);//翻转前target个字符
        reverse(password.begin()+target,password.end());//翻转后target个字符
        reverse(password.begin(),password.end());//翻转整个字符串
        return password;
    }
};

5.1用栈实现队列

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.pop();
            }
        }
        int result = 0;
        result = stOut.top();
        stOut.pop();
        return result;
    }
    
    int peek() {
        if(stOut.empty()){
            while(!stIn.empty()){
                stOut.push(stIn.top());
                stIn.pop();
            }
        }
        int result = 0;
        return result = stOut.top();

    }
    
    bool empty() {
        return stIn.empty()&&stOut.empty();
    }
};

5.2用队列实现栈

class MyStack {
public:
    queue<int> q1;
    queue<int> q2;
    MyStack() {

    }
    
    void push(int x) {
        q1.push(x);
    }
    
    int pop() {
        int size = q1.size();
        size--;
        while(size--){//留了一个元素在队列中
            q2.push(q1.front());//队头出
            q1.pop();
        }
        int result = q1.front();
        return result;
    }
    
    int top() {
        return  q1.back();
    }
    
    bool empty() {
        return q1.empty();
    }
};

5.2有效的括号

class Solution {
public:
    bool isValid(string s) {
        stack<char> st;
        if(s.size()%2 != 0)
            return false;
        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('}');
            else if(s[i]!=st.top()||st.empty()) return false;//字符串没结束,栈为空则返回失败
            else st.pop();
        }
        return st.empty();
    }
};
posted @ 2023-11-02 15:07  Ref-rain-  阅读(9)  评论(0)    收藏  举报