Longest Palindrome - Hash Table - Easy - LeetCode
💻 coding

Longest Palindrome - Hash Table - Easy - LeetCode

1 min read 146 words
1 min read
ShareWhatsAppPost on X
  • 1The problem requires finding the length of the longest palindrome that can be constructed from a given string of letters.
  • 2A hash table is used to count the occurrences of each character in the string for efficient palindrome length calculation.
  • 3The solution has a time complexity of O(n) and a space complexity of O(n), making it efficient for strings up to 2000 characters.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The problem requires finding the length of the longest palindrome that can be constructed from a given string of letters."

Longest Palindrome - Hash Table - Easy - LeetCode

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 Example 3:

Input: s = "bb" Output: 2

Constraints:

1 <= s.length <= 2000 s consits of lower-case and/or upper-case English letters only.

public class Solution {
 public int LongestPalindrome(string s) {
 var map = new Dictionary<char,int>();
 for(int i=0;i<s.Length;i++){
 if(map.ContainsKey(s[i])){
 map[s[i]]++;
 }
 else{
 map.Add(s[i],1);
 }
 }
 
 int count = 0;
 bool oddPossible = false;
 foreach(var item in map){
 if(item.Value%2==0){
 count+=item.Value;
 }
 else{
 count+=item.Value-1;
 oddPossible = true;
 }
 }
 
 return oddPossible?count+1:count;
 }
}

Time Complexity: O(n)

Space Complexity: O(n)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 28 September 2020 · 1 min read · 146 words

Part of AskGif Blog · coding

You might also like