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.
1using System;
2using System.Collections.Generic;
3
4class LongestPalindrome {
5 public static int LongestPalindrome(string s) {
6 Dictionary<char, int> frequency = new Dictionary<char, int>();
7 foreach (char c in s) {
8 if (frequency.ContainsKey(c)) {
9 frequency[c]++;
10 } else {
11 frequency[c] = 1;
12 }
13 }
14 int length = 0;
15 foreach (int count in frequency.Values) {
16 length += (count / 2) * 2;
17 if (count % 2 == 1 && length % 2 == 0) {
18 length++;
19 }
20 }
21 return length;
22 }
23
24 static void Main() {
25 string s = "abccccdd";
26 Console.WriteLine(LongestPalindrome(s)); // Output: 7
27 }
28}
In C#, we use a Dictionary to tally the occurrences of each character. The palindrome length is then constructed from the frequency data, handling even and odd occurrences differently.
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.