Skip to content

409. 最长回文串 #81

Description

@Geekhyt

原题链接

  1. 使用字母的 Unicode 编码和数组会比哈希表更优化
  2. 初始化存放字母出现次数的数组,默认都为 0 次
  3. 遍历字符串,统计字母出现的次数,65 是字母 A 的 Unicode 编码,这样可以从索引 0 开始计数
  4. time 的偶数次(time / 2)可以成为构造回文的一部分,再乘 2,可以得到次数
  5. 如果最后计算出的长度小于字符串的长度,则是奇数长度的回文,需要加 1
const longestPalindrome = function(s) {
     let arr = new Array(58).fill(0)
     
     for (let char of s) {
         arr[char.charCodeAt() - 65] += 1
     }

     let max = 0
     for (let time of arr) {
         max += parseInt((time / 2), 10) * 2
     }
     return max < s.length ? max + 1 : max
}
  • 时间复杂度: O(n)
  • 空间复杂度: O(n)

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions