牛客网算法题JS(三)NC141 判断是否为回文字符串

48 阅读1分钟

image.png

解题一: 首先想到js reverse方法,str.reverse不行,经搜索Array.reverse()。


/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 * 
 * @param str string字符串 待判断的字符串
 * @return bool布尔型
 */
function judge( str ) {
    // write code here
    const str1 = str.split('').reverse().join('')
    return str == str1
}
module.exports = {
    judge : judge
};

解题二: 因为杨先生说过尽量减少使用现成的函数。第二种想法:


/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 * 
 * @param str string字符串 待判断的字符串
 * @return bool布尔型
 */
function judge( str ) {
    // write code here
    const a = []
    for(let  i = str.length-1; i >= 0; i--) {
        a.push(str[i])
    }
    const str1 = a.join('')

    return str == str1

}
module.exports = {
    judge : judge
};