- Notifications
You must be signed in to change notification settings - Fork24
Open
Labels
Description
- 使用字母的 Unicode 编码和数组会比哈希表更优化
- 初始化存放字母出现次数的数组,默认都为 0 次
- 遍历字符串,统计字母出现的次数,65 是字母 A 的 Unicode 编码,这样可以从索引 0 开始计数
- time 的偶数次(time / 2)可以成为构造回文的一部分,再乘 2,可以得到次数
- 如果最后计算出的长度小于字符串的长度,则是奇数长度的回文,需要加 1
constlongestPalindrome=function(s){letarr=newArray(58).fill(0)for(letcharofs){arr[char.charCodeAt()-65]+=1}letmax=0for(lettimeofarr){max+=parseInt((time/2),10)*2}returnmax<s.length ?max+1 :max}
- 时间复杂度: O(n)
- 空间复杂度: O(n)