notes/OJ notes/pages/Leetcode Longest-Palindrome.md
2022-09-05 19:27:02 +08:00

2 KiB

Leetcode Longest-Palindrome

2022-09-05 17:27

Algorithms:

#algorithm #greedy

Data structures:

#DS #string

Difficulty:

#coding_problem #difficulty-easy

Additional tags:

#leetcode

Revisions:

N/A


Problem

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.

Examples

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.

Thoughts

[!summary] This is a #greedy problem.

The solution is simple: count the apperances, sort it using std::greater(), and select all even number, for odd number i:

  • if odd numbers has been used: ans += i - 1 (make it even)
  • if not: ans += i, and mark odd number used

Solution

class Solution {
public:
  int longestPalindrome(string s) {
    int ans = 0;
    bool used = false;
    vector<int> table(52, 0);

    // record in table.
    for (char ch : s) {
      if (ch <= 'Z') {
        table[ch - 'A' + 26]++;
      } else {
        table[ch - 'a']++;
      }
    }

    sort(table.begin(), table.end(), greater<int>());

    for (int i : table) {
      if (i % 2 == 1) {
        if (used == false) {
          used = true;
          ans += i;
        } else {
          ans += i - 1;
        }
      } else {
        if (i == 0) {
          break;
        }
        ans += i;
      }
    }

    return ans;
  }
};