[TypeScript 数据结构与算法-03]栈的实现与常见面试题😒

41 阅读1分钟

本文github地址:JavaScript_Everything 大前端知识体系与面试宝典,从前端到后端,全栈工程师,成为六边形战士


基于数组实现栈

定义栈接口

// 02.ts
interface Stack<T>{
    push(ele:T):void
    pop():T | undefined
    peek():T | undefined
    isEmpty():boolean
    size():number
}

export default Stack

实现栈的类

// 03.ts
class Stack<T=string> {
    private data: T[] = []

    push(ele:T):void{
        this.data.push(ele)
    }

    pop():T | undefined{
        return this.data.pop()
    }

    peek():T | undefined{
        return this.data[this.data.length-1]
    }

    isEmpty():boolean{
        return this.data.length === 0
    }

    size():number{
        return this.data.length
    }
}

栈的面试题

十进制转二进制

除 2 直到 0,将余数结果倒排,越往后的数越在高位

// Codes/算法/栈/04.ts
function decimalToBinary(decimal:number):string{
    const stack = new Array()
    while(decimal>0){
        const result = decimal % 2
        stack.push(result)
        decimal = Math.floor(decimal/2)
    }
    let res = ''
    while(stack.length){
        res += stack.pop()
    }

    return res
}

console.log(decimalToBinary(35)) // 100011

有效的括号

leetcode 链接 20.有效的括号

题目描述:

给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。

有效字符串需满足:

左括号必须用相同类型的右括号闭合。

左括号必须以正确的顺序闭合。

每个右括号都有一个对应的相同类型的左括号。   示例 1:

输入:s = "()" 输出:true

题解 :

function isValid(str:string):boolean{
    const stack = new Array<string>();
    for (let index = 0; index < str.length; index++) {
        const element = str[index];
        switch(element){
            case '(':
                stack.push(')')
                break
            case '{':
                stack.push('}')
                 break
            case '[':
                stack.push(']')
                break
            default:
                if(element !== stack.pop()) return false
                break
        }
    }
    return stack.length === 0
}

console.log(isValid('[[[]]]')) // true
console.log(isValid('[[[}]]]')) // false

代码优化

function isValid2(str:string):boolean{
    const stack = new Array<string>();
    const map = new Map([
        [')', '('],
        [']', '['],
        ['}', '{'],
    ]);
    if(str.length === 0 || str[0] in map) return false;
    for(let i=0;i<str.length;i++){
        const ele = str[i]
        if(map.get(ele)){
            if(map.get(ele) !== stack.pop()) return false;
        }else{
            stack.push(str[i]);
        }
    }
    return stack.length === 0;
}

console.log(isValid2('[[[]]]')) // true
console.log(isValid2('[[[]]}]')) // false

本文github地址:JavaScript_Everything 大前端知识体系与面试宝典,从前端到后端,全栈工程师,成为六边形战士