| | 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 | | using System.Text; |
| | 13 | |
|
| | 14 | | namespace LeetCode.Algorithms.FindLongestSpecialSubstringThatOccursThrice1; |
| | 15 | |
|
| | 16 | | /// <inheritdoc /> |
| | 17 | | public class FindLongestSpecialSubstringThatOccursThrice1Dictionary : IFindLongestSpecialSubstringThatOccursThrice1 |
| | 18 | | { |
| | 19 | | /// <summary> |
| | 20 | | /// Time complexity - O(n^2) |
| | 21 | | /// Space complexity - O(n^2) |
| | 22 | | /// </summary> |
| | 23 | | /// <param name="s"></param> |
| | 24 | | /// <returns></returns> |
| | 25 | | public int MaximumLength(string s) |
| 3 | 26 | | { |
| 3 | 27 | | var dictionary = new Dictionary<string, int>(); |
| | 28 | |
|
| 38 | 29 | | for (var i = 0; i < s.Length; i++) |
| 16 | 30 | | { |
| 16 | 31 | | var substring = new StringBuilder(); |
| | 32 | |
|
| 76 | 33 | | for (var j = i; j < s.Length && s[j] == s[i]; j++) |
| 22 | 34 | | { |
| 22 | 35 | | substring.Append(s[j]); |
| | 36 | |
|
| 22 | 37 | | var key = substring.ToString(); |
| | 38 | |
|
| 22 | 39 | | if (!dictionary.TryAdd(key, 1)) |
| 9 | 40 | | { |
| 9 | 41 | | dictionary[key]++; |
| 9 | 42 | | } |
| 22 | 43 | | } |
| 16 | 44 | | } |
| | 45 | |
|
| 16 | 46 | | return dictionary.Where(keyValuePair => keyValuePair.Value >= 3) |
| 3 | 47 | | .Select(keyValuePair => keyValuePair.Key.Length) |
| 3 | 48 | | .DefaultIfEmpty(-1) |
| 3 | 49 | | .Max(); |
| 3 | 50 | | } |
| | 51 | | } |