leohxj
5/29/2014 - 7:04 AM

反转字符串, 效率的话iterative ,hack ,m5较高。测试地址为:http://jsperf.com/string-reverse-compare/5

反转字符串, 效率的话iterative ,hack ,m5较高。测试地址为:http://jsperf.com/string-reverse-compare/5

// iterative

function string_reverse_1(str) {
    var new_str = "";
    for (var i = str.length - 1; i >= 0; i--) {
        new_str += str.charAt(i);
    }
    return new_str;
}

// Hack 
function string_reverse_1_hack(str) {
    var new_str = "";
    for (var i = str.length - 1; i >= 0; i--) {
        new_str += str[i];
    }
    return new_str;
}

// iterative (m5)
function string_reverse_1b(str) {
    var s = str,
        new_str = "";
    for (var i = s.length; --i >= 0; new_str += s[i]);
    return new_str;
}

// iterative swapping
function string_reverse_2(str) {
    if (str.length < 1) return "";

    str = str.split(""); // make the string an array!
    var tmp, len = str.length,
        half_index = Math.floor(len / 2) - 1;;
    for (var i = 0; i <= half_index; i++) {
        tmp = str[len - i - 1];
        str[len - i - 1] = str[i];
        str[i] = tmp;
    }

    return str.join(""); // make the array a string again
}

// built-ins
function string_reverse_3(str) {
    return str.split("").reverse().join("");
}

// recursive: reverse(str.substr(1)) + str[0]
function string_reverse_4(str) {
    if (str.length < 2) return str;
    return string_reverse_4(str.substr(1)) + str.charAt(0);
}

// recursive: reverse(str.last_half()) + reverse(str.first_half())
function string_reverse_5(str) {
    if (str.length < 2) return str;

    var half_index = Math.ceil(str.length / 2);
    return string_reverse_5(str.substr(half_index)) + string_reverse_5(str.substr(0, half_index));
}