代码随想录算法训练营第十天| 232.用栈实现队列 、 225. 用队列实现栈 、 20. 有效的括号 、 1047. 删除字符串中的所有相邻重复项

48 阅读1分钟

232.用栈实现队列

相关链接: 题目链接 文章讲解 视频讲解

解题思路

js中数组模拟队列

代码


var MyQueue = function() {
    this.queue = [];
};

/** 
 * @param {number} x
 * @return {void}
 */
MyQueue.prototype.push = function(x) {
    this.queue.push(x);
};

/**
 * @return {number}
 */
MyQueue.prototype.pop = function() {
    return this.queue.shift();
};

/**
 * @return {number}
 */
MyQueue.prototype.peek = function() {
    return this.queue[0];
};

/**
 * @return {boolean}
 */
MyQueue.prototype.empty = function() {
    if(this.queue.length==0){
        return true;
    }else{
        return false;
    }
};

225. 用队列实现栈

相关链接: 题目链接 文章讲解 视频讲解

解题思路

代码

let MyStack = function() {
    this.queue = [];
    this._queue = [];
};

MyStack.prototype.push = function(x) {
    this.queue.push(x);
};

MyStack.prototype.pop = function() {
    while(this.queue.length > 1){
        this._queue.push(this.queue.shift());
    }
    let ans = this.queue.shift();
    while(this._queue.length){
        this.queue.push(this._queue.shift());
    }
    return ans;
};

MyStack.prototype.top = function() {
    return this.queue.slice(-1)[0];
};

MyStack.prototype.empty = function() {
    return !this.queue.length;
};

20. 有效的括号

相关链接: 题目链接 文章讲解 视频讲解

解题思路

代码

var isValid = function(s) {
    var stack = [];
    for(let i =0; i<s.length; i++){
        if(s[i] === '(' || s[i] ==='[' || s[i] ==='{'){
            stack.push(s[i]);
        }else{
            if((stack[stack.length - 1] === '(' && s[i] === ')')||(stack[stack.length - 1] === '[' && s[i] === ']') ||(stack[stack.length - 1] === '{' && s[i] === '}') ){
                 stack.pop();
            }else{
                return false;
            }
        }
    }
    if(stack.length === 0){
        return true;
    }
    return false;
    

1047. 删除字符串中的所有相邻重复项

相关链接: 题目链接 文章讲解 视频讲解

解题思路

代码

var removeDuplicates = function(s) {
    var arr = Array.from(s);
    let slow = 0, fast = 1;
    while(fast < arr.length){
        if(arr[fast] === arr[fast-1]){
            arr.splice(fast-1,2);
            fast = fast - 2 >= 0 ? fast-2: 0;
        }else{ 
            fast++;
        }
    }
    return arr.join('');
};