【Leetcode 409 】 最长回文串 —— 偶数相消

47 阅读1分钟

 给定一个包含大写字母和小写字母的字符串 s ,返回通过这些字母构造成的 最长的回文串的长度。

在构造过程中,请注意 区分大小写 。比如 "Aa" 不能当做一个回文字符串。

示例 1:

输入: s = "abccccdd"
输出: 7
解释:
我们可以构造的最长的回文串是"dccaccd", 它的长度是 7

示例 2:

输入: s = "a"
输出: 1
解释: 可以构造的最长回文串是"a",它的长度是 1

偶数相消 

function longestPalindrome(s: string): number {
  if (s.length < 1) return 1;
  let res = 0;
  const evenSet = new Set<string>();
  for (const v of s) {
    if (evenSet.has(v)) {
      res += 2;
      evenSet.delete(v);
    } else {
      evenSet.add(v);
    }
  }
  return res < s.length ? ++res : res;
}