Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

409. 最长回文串 #81

Open
Geekhyt opened this issue Sep 19, 2021 · 0 comments
Open

409. 最长回文串 #81

Geekhyt opened this issue Sep 19, 2021 · 0 comments
Labels

Comments

@Geekhyt
Copy link
Owner

Geekhyt commented Sep 19, 2021

原题链接

  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)
@Geekhyt Geekhyt added the 简单 label Sep 19, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant