HJ32 密码截取

2023-08-22  本文已影响0人  vivienYang2019

https://www.nowcoder.com/questionTerminal/3cd4621963e8454594f00199f4536bb1?answerType=1&f=discussion
我的解法:耗时比较久

const rl = require("readline").createInterface({ input: process.stdin });
let max = 1;
rl.on("line", function (input) {
   for (let i = 0; i < input.length; i++) {
       let cha = input[i];
       let last_index = input.lastIndexOf(cha);
       if (i < last_index) {
           for (k = last_index; i < k; k--) {
               let sub_str = input.slice(i, k + 1);
               if (
                   sub_str.length > max &&
                   input[i] === input[k] &&
                   isLoop(sub_str)
               ) {
                   max = sub_str.length;
               }
           }
       }
   }
   console.log(max);
});
function isLoop(str) {
   let left = 0,
       right = str.length - 1;
   while (left < right) {
       if (str[left] !== str[right]) return false;
       left++;
       right--;
   }
   return true;
}

别人的解法,耗时内存都减半

var readline = require('readline')
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
rl.on('line', (str)=> {
    var max = 0;
    // 当最长回文子串的长度是奇数时
    for(let i=0; i<str.length; i++){
        let n = i-1;
        let m = i+1;
        while(n>=0 && m<str.length && str[n] == str[m]){
            max = Math.max(m-n+1, max);
            n--;
            m++;
        }
    }
    // 当最长回文子串的长度是偶数时
    for(let i=0; i<str.length; i++){
        let n = i;
        let m = i+1;
        while(n>=0 && m<str.length && str[n] == str[m]){
            max = Math.max(m-n+1, max);
            n--;
            m++;
        }
    }
    console.log(max);
})
上一篇下一篇

猜你喜欢

热点阅读