| | | 1 | | // -------------------------------------------------------------------------------- |
| | | 2 | | // Copyright (C) 2026 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.CheckIfStringsCanBeMadeEqualWithOperations2; |
| | | 13 | | |
| | | 14 | | /// <inheritdoc /> |
| | | 15 | | public sealed class CheckIfStringsCanBeMadeEqualWithOperations2FrequencyArray : |
| | | 16 | | ICheckIfStringsCanBeMadeEqualWithOperations2 |
| | | 17 | | { |
| | | 18 | | private const byte AlphabetLength = 'z' - 'a' + 1; |
| | | 19 | | |
| | | 20 | | /// <summary> |
| | | 21 | | /// Time complexity - O(n) |
| | | 22 | | /// Space complexity - O(1) |
| | | 23 | | /// </summary> |
| | | 24 | | /// <param name="s1"></param> |
| | | 25 | | /// <param name="s2"></param> |
| | | 26 | | /// <returns></returns> |
| | | 27 | | public bool CheckStrings(string s1, string s2) |
| | 20 | 28 | | { |
| | 20 | 29 | | Span<int> evenFrequencies = stackalloc int[AlphabetLength]; |
| | 20 | 30 | | Span<int> oddFrequencies = stackalloc int[AlphabetLength]; |
| | | 31 | | |
| | 242 | 32 | | for (var i = 0; i < s1.Length; i++) |
| | 101 | 33 | | { |
| | 101 | 34 | | var index1 = GetIndex(s1[i]); |
| | 101 | 35 | | var index2 = GetIndex(s2[i]); |
| | | 36 | | |
| | 101 | 37 | | if (i % 2 == 0) |
| | 52 | 38 | | { |
| | 52 | 39 | | evenFrequencies[index1]++; |
| | 52 | 40 | | evenFrequencies[index2]--; |
| | 52 | 41 | | } |
| | | 42 | | else |
| | 49 | 43 | | { |
| | 49 | 44 | | oddFrequencies[index1]++; |
| | 49 | 45 | | oddFrequencies[index2]--; |
| | 49 | 46 | | } |
| | 101 | 47 | | } |
| | | 48 | | |
| | 806 | 49 | | for (var i = 0; i < AlphabetLength; i++) |
| | 390 | 50 | | { |
| | 390 | 51 | | if (oddFrequencies[i] == 0 && evenFrequencies[i] == 0) |
| | 383 | 52 | | { |
| | 383 | 53 | | continue; |
| | | 54 | | } |
| | | 55 | | |
| | 7 | 56 | | return false; |
| | | 57 | | } |
| | | 58 | | |
| | 13 | 59 | | return true; |
| | 20 | 60 | | } |
| | | 61 | | |
| | | 62 | | private static int GetIndex(char c) |
| | 202 | 63 | | { |
| | 202 | 64 | | return c - 'a'; |
| | 202 | 65 | | } |
| | | 66 | | } |