【问题标题】:Largest possible palindromic substring of a given string in JavaScriptJavaScript 中给定字符串的最大可能回文子串
【发布时间】:2020-06-23 19:17:37
【问题描述】:

这是我被要求写的一个面试问题。时间复杂度应该很小。我无法为这个问题写一个合适的解决方案。

问题:JavaScript 中给定字符串的最大可能回文子字符串

【问题讨论】:

  • 是的,你是对的,返回字符串应该是最长的子字符串。
  • 字符串应该是最长的回文。这是我的错误让我更新问题。
  • 好的,这让它更有趣了。尽管如此,请提供一些代码。
  • 你的问题漏掉了很多。您的尝试在哪里,明确的问题是什么?最大的 Palendrome 是入门级编程演出的一个非常常见的问题。请发布您的尝试,让我们引导您解决问题!
  • Manacher 算法 hackerrank.com/topics/manachers-algorithm 具有 O(N) 时间复杂度

标签: algorithm data-structures


【解决方案1】:

请通过以下代码:

var longestPalindrome = function(string) {

  var length = string.length;
  var result = "";

  var centeredPalindrome = function(left, right) {
    while (left >= 0 && right < length && string[left] === string[right]) {
      //expand in each direction.
      left--;
      right++;
    }

    return string.slice(left + 1, right);
  };

  for (var i = 0; i < length - 1; i++) {
    var oddPal = centeredPalindrome(i, i + 1);

    var evenPal = centeredPalindrome(i, i);

    if (oddPal.length > 1)
      console.log("oddPal: " + oddPal);
    if (evenPal.length > 1)
      console.log("evenPal: " + evenPal);

    if (oddPal.length > result.length)
      result = oddPal;
    if (evenPal.length > result.length)
      result = evenPal;
  }
  return "the palindrome is: " + result + " and its length is: " + result.length;
};

console.log(
  longestPalindrome("nan noon is redder")
);

致谢:@Paul Roub

【讨论】:

  • 感谢您的帮助
猜你喜欢
  • 2022-01-16
  • 2021-04-14
  • 2020-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-23
  • 1970-01-01
相关资源
最近更新 更多