Manacher's algorithm (algorithm to find longest palindrome substring in linear time)

前端 未结 10 553
走了就别回头了
走了就别回头了 2020-12-22 16:02

After spending about 6-8 hours trying to digest the Manacher\'s algorithm, I am ready to throw in the towel. But before I do, here is one last shot in the dark: can anyone e

10条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-22 16:33

    Fast Javascript Solution to finding the longest palindrome in a string:

    const lpal = str => {
      let lpal = ""; // to store longest palindrome encountered
      let pal = ""; // to store new palindromes found
      let left; // to iterate through left side indices of the character considered to be center of palindrome
      let right; // to iterate through left side indices of the character considered to be center of palindrome
      let j; // to iterate through all characters and considering each to be center of palindrome
      for (let i=0; i= 0 && right < str.length) { // while left and right indices exist
          if(str[left] === str[right]) { //
            pal = str[left] + pal + str[right];
          } else {
            break;
          }
          left--;
          right++;
        }
        if(pal.length > lpal.length) {
          lpal = pal;
        }
        pal = str[i];
        j = i;
        left = j-1;
        right = j+1;
        if(str[j] === str[right]) {
          pal = pal + str[right];
          right++;
          while (left >= 0 && right < str.length) {
            if(str[left] === str[right]) {
              pal = str[left] + pal + str[right];
            } else {
              break;
            }
            left--;
            right++;
          }
          if(pal.length > lpal.length) {
            lpal = pal;
          }
        }
      }
      return lpal;
    }
    

    Example Input

    console.log(lpal("gerngehgbrgregbeuhgurhuygbhsbjsrhfesasdfffdsajkjsrngkjbsrjgrsbjvhbvhbvhsbrfhrsbfsuhbvsuhbvhvbksbrkvkjb"));
    

    Output

    asdfffdsa
    

提交回复
热议问题