返回介绍

solution / 0400-0499 / 0409.Longest Palindrome / README_EN

发布于 2024-06-17 01:04:00 字数 4936 浏览 0 评论 0 收藏 0

409. Longest Palindrome

中文文档

Description

Given a string s which consists of lowercase or uppercase letters, return _the length of the longest palindrome_ that can be built with those letters.

Letters are case sensitive, for example, "Aa" is not considered a palindrome here.

 

Example 1:

Input: s = "abccccdd"
Output: 7
Explanation: One longest palindrome that can be built is "dccaccd", whose length is 7.

Example 2:

Input: s = "a"
Output: 1
Explanation: The longest palindrome that can be built is "a", whose length is 1.

 

Constraints:

  • 1 <= s.length <= 2000
  • s consists of lowercase and/or uppercase English letters only.

Solutions

Solution 1: Counting

A valid palindrome string can have at most one character that appears an odd number of times, and the rest of the characters appear an even number of times.

Therefore, we can first traverse the string $s$, count the number of times each character appears, and record it in an array or hash table $cnt$.

Then, we traverse $cnt$, for each character $c$, if $cnt[c]$ is even, then directly add $cnt[c]$ to the answer $ans$; if $cnt[c]$ is odd, then add $cnt[c] - 1$ to $ans$, if $ans$ is even, then increase $ans$ by $1$.

Finally, we return $ans$.

The time complexity is $O(n)$, and the space complexity is $O(C)$. Here, $n$ is the length of the string $s$; and $C$ is the size of the character set, in this problem $C = 128$.

class Solution:
  def longestPalindrome(self, s: str) -> int:
    cnt = Counter(s)
    ans = 0
    for v in cnt.values():
      ans += v - (v & 1)
      ans += (ans & 1 ^ 1) and (v & 1)
    return ans
class Solution {
  public int longestPalindrome(String s) {
    int[] cnt = new int[128];
    for (int i = 0; i < s.length(); ++i) {
      ++cnt[s.charAt(i)];
    }
    int ans = 0;
    for (int v : cnt) {
      ans += v - (v & 1);
      if (ans % 2 == 0 && v % 2 == 1) {
        ++ans;
      }
    }
    return ans;
  }
}
class Solution {
public:
  int longestPalindrome(string s) {
    int cnt[128]{};
    for (char& c : s) {
      ++cnt[c];
    }
    int ans = 0;
    for (int v : cnt) {
      ans += v - (v & 1);
      if (ans % 2 == 0 && v % 2 == 1) {
        ++ans;
      }
    }
    return ans;
  }
};
func longestPalindrome(s string) (ans int) {
  cnt := [128]int{}
  for _, c := range s {
    cnt[c]++
  }
  for _, v := range cnt {
    ans += v - (v & 1)
    if ans&1 == 0 && v&1 == 1 {
      ans++
    }
  }
  return
}
function longestPalindrome(s: string): number {
  let n = s.length;
  let ans = 0;
  let record = new Array(128).fill(0);
  for (let i = 0; i < n; i++) {
    record[s.charCodeAt(i)]++;
  }
  for (let i = 65; i < 128; i++) {
    let count = record[i];
    ans += count % 2 == 0 ? count : count - 1;
  }
  return ans < s.length ? ans + 1 : ans;
}
use std::collections::HashMap;

impl Solution {
  pub fn longest_palindrome(s: String) -> i32 {
    let mut map: HashMap<char, i32> = HashMap::new();
    for c in s.chars() {
      map.insert(c, map.get(&c).unwrap_or(&0) + 1);
    }
    let mut has_odd = false;
    let mut res = 0;
    for v in map.values() {
      res += v;
      if v % 2 == 1 {
        has_odd = true;
        res -= 1;
      }
    }
    res + (if has_odd { 1 } else { 0 })
  }
}

Solution 2

function longestPalindrome(s: string): number {
  const map = new Map();
  for (const c of s) {
    map.set(c, (map.get(c) ?? 0) + 1);
  }
  let hasOdd = false;
  let res = 0;
  for (const v of map.values()) {
    res += v;
    if (v & 1) {
      hasOdd = true;
      res--;
    }
  }
  return res + (hasOdd ? 1 : 0);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文