数据结构篇(1) ts实现栈的基本操作和解决相关问题

interface Stack {
    _items: any
    push(element: any): void
    pop(): any
    top(): any
    size(): any
    isEmpty(): any
    clear(): any
}
//用Symbol添加私有属性
class Stack {
    _items: any = Symbol()

    constructor() {
        this._items = []
    }

    push(element: any): void {
        this._items.push(element);
    }

    pop(): any {
        let r: any = this._items.pop();
        return r;
    }

    size(): number {
        return this._items.length;
    }
    top(): number {
        return this._items[this.size() - 1];
    }
    isEmpty(): boolean {
        if (this._items.length === 0) {
            return true;
        }
        return false;
    }
    clear() {
        this._items = [];
    }
}

let newStack = new Stack();
//十进制转换二进制
function devideBy2(num: any): void {
    while (num != 0) {
        newStack.push(num % 2);
        num = num / 2;
        num = parseInt(num);
    }

    let num2 = 0;

    while ((num2 = newStack.pop()) != null) {
        console.log(num2)
    }
}

//const opens = ``
//const closers = `)]}`
//平衡括号 正常方法
/** 
function balancedSymbols(symbols:string) {
    let index:number = 0;
    let balanced:boolean = true;
    let symbol:string = symbols[index];
    while(index<symbols.length&&balanced) {
        if(symbol === "[" || symbol === "("|| symbol === "{") {
            newStack.push(symbol);
        } else {
            switch(symbol) {
                case "]": {
                    if(newStack.pop() != '[') {
                        return false;
                    }
                    break;
                }
                case "}": {
                    if(newStack.pop() != '{') {
                        return false;
                    }
                    break;
                }
                case ")": {
                    if(newStack.pop() != '(') {
                        return false;
                    }
                    break;
                }
            }
        }
        symbol = symbols[++index];
    }
    return true;
}
*/
//递归实现
function balancedSymbols(symbols: string): any {
    if(!symbols.length) {
        return true;
    }
    let symbol: string = symbols.slice(0, 1);
    symbols = symbols.slice(1);

    switch (symbol) {
        case '(': case '[': case '{': {
            console.log(symbol)
            newStack.push(symbol);
            break;
        }
        case ')': {
            if (newStack.pop() != '(') {
                return false;
            }
            break;
        } 
        case ']': {
            if (newStack.pop() != '[') {
                return false;
            }
            break;
        } case '}': {
            if (newStack.pop() != '{') {
                return false;
            }
            break;
        }
    }
    return balancedSymbols(symbols);
}
devideBy2(10);
console.log(balancedSymbols('([{])'))


posted @ 2022-03-28 12:04  ajajaz  阅读(114)  评论(0编辑  收藏  举报