| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.LongestPalindrome; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class LongestPalindromeDictionary : ILongestPalindrome |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n) |
| | 19 | | /// Space complexity - O(n) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="s"></param> |
| | 22 | | /// <returns></returns> |
| | 23 | | public int LongestPalindrome(string s) |
| 6 | 24 | | { |
| 6 | 25 | | if (string.IsNullOrEmpty(s)) |
| 1 | 26 | | { |
| 1 | 27 | | return 0; |
| | 28 | | } |
| | 29 | |
|
| 5 | 30 | | var charCount = new Dictionary<char, int>(); |
| | 31 | |
|
| 2982 | 32 | | foreach (var c in s.Where(c => !charCount.TryAdd(c, 1))) |
| 977 | 33 | | { |
| 977 | 34 | | charCount[c]++; |
| 977 | 35 | | } |
| | 36 | |
|
| 5 | 37 | | var length = 0; |
| 5 | 38 | | var oddCountFound = false; |
| | 39 | |
|
| 87 | 40 | | foreach (var count in charCount.Values) |
| 36 | 41 | | { |
| 36 | 42 | | if (count % 2 == 0) |
| 15 | 43 | | { |
| 15 | 44 | | length += count; |
| 15 | 45 | | } |
| | 46 | | else |
| 21 | 47 | | { |
| 21 | 48 | | length += count - 1; |
| 21 | 49 | | oddCountFound = true; |
| 21 | 50 | | } |
| 36 | 51 | | } |
| | 52 | |
|
| 5 | 53 | | if (oddCountFound) |
| 4 | 54 | | { |
| 4 | 55 | | length++; |
| 4 | 56 | | } |
| | 57 | |
|
| 5 | 58 | | return length; |
| 6 | 59 | | } |
| | 60 | | } |