Sponsored
Sponsored
This approach involves counting the frequency of each character in the string and calculating the length of the longest possible palindrome based on those frequencies. The key insight is that even frequency counts can completely contribute to a palindrome, while only one odd frequency character can be used once in the center of the palindrome.
Time Complexity: O(n) - where n is the length of the string as we iterate through the string to count character frequencies.
Space Complexity: O(1) - We only use a fixed-size array of 128 elements to store character frequencies.
1#include <iostream>
2#include <unordered_map>
3#include <string>
4using namespace std;
5
6int longestPalindrome(string s) {
7 unordered_map<char, int> frequency;
8 for (char c : s) {
9 frequency[c]++;
10 }
11 int length = 0;
12 for (const auto& [char, count] : frequency) {
13 length += (count / 2) * 2;
14 if (count % 2 == 1 && length % 2 == 0) {
15 length++;
16 }
17 }
18 return length;
19}
20
21int main() {
22 string s = "abccccdd";
23 cout << longestPalindrome(s) << endl; // Output: 7
24 return 0;
25}
This C++ solution utilizes an unordered_map to count character frequencies and determine the longest palindrome length in a similar manner as the C solution.
This approach leverages a set data structure to efficiently keep track of characters with odd frequencies. A character encountered an odd number of times will toggle its presence in the set. The result is derived from the total number of characters and the size of this set.
Time Complexity: O(n) - Each character is processed independently.
Space Complexity: O(1) - Fixed memory allocation for set representation.
1
This Java technique uses a HashSet to efficiently toggle character presence for odd frequency tracking, affecting the final length based on odd set size.