字符串逆序输出的算法

不说了,直接贴代码:

/**
 * StringReverse用于处理字符串逆序输出的算法,
 * 时间:2022-02-24
 * 
 * 来源:javascript重难点实例精讲
 */

//定义一个字符串
var str = 'abcdefg';

/**
 * 算法1:采用数组的reverse()实现逆序
 */
function reverseString1(str) {
    return str.split('').reverse().join('');
}

/**
 * 算法2:利用字符串的charAt()
 */
function reverseString2(str) {
    let result = '';
    for (let i = str.length; i >= 0; i--) {
        result += str.charAt(i);
    }
    return result;
}

/**
 * 算法3:使用递归
 * 
 * 会用到charAt(),涉及到的参数:字符串、位置、返回值(拼接字符串)
 */
function reverseString3(str, result = '', pos = str.length - 1) {
    if (pos < 0) {
        return result;
    }
    result += str.charAt(pos--);
    return reverseString3(str, result, pos);
}

/**
 * 算法4:改变slice()执行主体
 */
function reverseString4(str) {
    return Array.prototype.slice.call(str).reverse().join('');
}

/**
 * 算法5:使用栈, 要在栈定义之后调用栈,否则会出现异常
 */

//定义一个栈

//使用类创建栈的时候,在栈声明之前调用栈,会出现初始化前调用类的异常
//Cannot access 'Stack' before initialization
class Stack {
    constructor() {
        this.data = []; //保存栈内元素
        this.top = 0; //记录栈顶位置
    }

    //入栈:先在栈顶添加元素,然后元素个数加1
    push(element) {
        this.data[this.top++] = element;
    }

    //出栈:先返回栈顶元素,然后元素个数减1
    pop() {
        return this.data[--this.top];
    }

    length() {
        return this.top;
    }

    toString() {
        return this.data.toString() + ',[class]';
    }
}

// //使用函数创建栈,在栈声明之前调用栈,会出现异常
// //s.push is not a function
// function Stack() {
//     this.data = [];
//     this.top = 0;
// }

// Stack.prototype = {
//     push: function (element) {
//         this.data[this.top++] = element;
//     },
//     pop: function () {
//         return this.data[--this.top];
//     },
//     length: function () {
//         return this.top;
//     },
//     toString: function () {
//         return this.data.toSgtring() + ',[function]';
//     },
// }

function reverseString5(str) {
    let s = new Stack();
    let arr = str.split('');
    let result = '';
    for (const i of arr) {
        if (i) {
            s.push(i);
        }
    }

    while (s.length()) {
        result += s.pop();
    }
    // console.log(s.toString());
    return result;
}


console.log(reverseString1(str)); //gfedcba
console.log(reverseString2(str)); //gfedcba
console.log(reverseString3(str)); //gfedcba
console.log(reverseString4(str)); //gfedcba
console.log(reverseString5(str)); //gfedcba
posted @ 2022-02-24 10:59  晨米酱  阅读(255)  评论(0编辑  收藏  举报