Skip to content

409. 最长回文串

js
;(function () {
  /**
   * 409. 最长回文串
   * 【回文串是一个正着读和反着读都一样的字符串。】
   * 给定一个包含大写字母和小写字母的字符串 s ,返回 通过这些字母构造成的 最长的回文串 。
   * 在构造过程中,请注意 区分大小写 。比如 "Aa" 不能当做一个回文字符串。
   *
   * 输入:s = "abccccdd"
   * 输出:7
   * 解释:
   * 我们可以构造的最长的回文串是"dccaccd", 它的长度是 7。
   *
   * 输入:s = "a"
   * 输入:1
   *
   * 输入:s = "bb"
   * 输入: 2
   *
   */

  function longestPalindrome(s: string): number {
    // 方法一:
    if (!s) return 0
    let strArr: string[] = s.split('')
    strArr.sort((a: string, b: string) => a.charCodeAt(0) - b.charCodeAt(0))
    // console.log(strArr)
    let total = 0
    let tempCount = 1
    for (let i = 0; i < strArr.length; i++) {
      if (strArr[i] === strArr[i + 1]) {
        tempCount++
      } else {
        tempCount > 1 ? (total += Math.floor(tempCount / 2)) : null
        tempCount = 1
      }
    }
    return total * 2 < strArr.length ? total * 2 + 1 : total * 2

    // 方法二:
  }

  const s = 'abccccdd'
  const s2 = 'a'
  const s3 = 'bb'
  const s4 = 'ccc'
  const s5 = 'abccccdd'
  console.log(longestPalindrome(s))
  console.log(longestPalindrome(s2))
  console.log(longestPalindrome(s3))
  console.log(longestPalindrome(s4))
  console.log(longestPalindrome(s5))
})()