| | 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.LongestPalindromeByConcatenatingTwoLetterWords; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class LongestPalindromeByConcatenatingTwoLetterWordsFrequencyArray : |
| | 16 | | ILongestPalindromeByConcatenatingTwoLetterWords |
| | 17 | | { |
| | 18 | | private const int Length = 'z' - 'a' + 1; |
| | 19 | |
|
| | 20 | | /// <summary> |
| | 21 | | /// Time complexity - O(n) |
| | 22 | | /// Space complexity - O(1) |
| | 23 | | /// </summary> |
| | 24 | | /// <param name="words"></param> |
| | 25 | | /// <returns></returns> |
| | 26 | | public int LongestPalindrome(string[] words) |
| 3 | 27 | | { |
| 3 | 28 | | var longestPalindrome = 0; |
| | 29 | |
|
| 3 | 30 | | var frequencyArray = new int[Length, Length]; |
| | 31 | |
|
| 33 | 32 | | foreach (var word in words) |
| 12 | 33 | | { |
| 12 | 34 | | var a = word[0] - 'a'; |
| 12 | 35 | | var b = word[1] - 'a'; |
| | 36 | |
|
| 12 | 37 | | if (frequencyArray[b, a] > 0) |
| 3 | 38 | | { |
| 3 | 39 | | longestPalindrome += 4; |
| | 40 | |
|
| 3 | 41 | | frequencyArray[b, a]--; |
| 3 | 42 | | } |
| | 43 | | else |
| 9 | 44 | | { |
| 9 | 45 | | frequencyArray[a, b]++; |
| 9 | 46 | | } |
| 12 | 47 | | } |
| | 48 | |
|
| 74 | 49 | | for (var i = 0; i < Length; i++) |
| 36 | 50 | | { |
| 36 | 51 | | if (frequencyArray[i, i] > 0) |
| 2 | 52 | | { |
| 2 | 53 | | return longestPalindrome + 2; |
| | 54 | | } |
| 34 | 55 | | } |
| | 56 | |
|
| 1 | 57 | | return longestPalindrome; |
| 3 | 58 | | } |
| | 59 | | } |