| | | 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.NumberOfWonderfulSubstrings; |
| | | 13 | | |
| | | 14 | | /// <inheritdoc /> |
| | | 15 | | public sealed class NumberOfWonderfulSubstringsDictionary : INumberOfWonderfulSubstrings |
| | | 16 | | { |
| | | 17 | | /// <summary> |
| | | 18 | | /// Time complexity - O(n * k), where n is the length of the string and k is the number of characters in the alp |
| | | 19 | | /// (which is constant, k = 10) |
| | | 20 | | /// Space complexity - O(n) |
| | | 21 | | /// </summary> |
| | | 22 | | /// <param name="word"></param> |
| | | 23 | | /// <returns></returns> |
| | | 24 | | public long WonderfulSubstrings(string word) |
| | 3 | 25 | | { |
| | 3 | 26 | | long count = 0; |
| | | 27 | | |
| | 3 | 28 | | var bitmask = 0; |
| | | 29 | | |
| | 3 | 30 | | var maskCount = new Dictionary<int, int> { [0] = 1 }; |
| | | 31 | | |
| | 27 | 32 | | foreach (var c in word) |
| | 9 | 33 | | { |
| | 9 | 34 | | bitmask ^= 1 << (c - 'a'); |
| | | 35 | | |
| | 9 | 36 | | if (maskCount.TryGetValue(bitmask, out var bitmaskCount)) |
| | 2 | 37 | | { |
| | 2 | 38 | | count += bitmaskCount; |
| | 2 | 39 | | } |
| | | 40 | | |
| | 198 | 41 | | for (var i = 0; i < 10; i++) |
| | 90 | 42 | | { |
| | 90 | 43 | | var tempMask = bitmask ^ (1 << i); |
| | | 44 | | |
| | 90 | 45 | | if (maskCount.TryGetValue(tempMask, out var tempMaskCount)) |
| | 11 | 46 | | { |
| | 11 | 47 | | count += tempMaskCount; |
| | 11 | 48 | | } |
| | 90 | 49 | | } |
| | | 50 | | |
| | 9 | 51 | | if (!maskCount.TryAdd(bitmask, 1)) |
| | 2 | 52 | | { |
| | 2 | 53 | | maskCount[bitmask]++; |
| | 2 | 54 | | } |
| | 9 | 55 | | } |
| | | 56 | | |
| | 3 | 57 | | return count; |
| | 3 | 58 | | } |
| | | 59 | | } |