| | 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.LargestThreeSameDigitNumberInString; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class LargestThreeSameDigitNumberInStringGreedyOptimized : ILargestThreeSameDigitNumberInString |
| | 16 | | { |
| 1 | 17 | | private static readonly string[] Triples = |
| 1 | 18 | | [ |
| 1 | 19 | | "000", "111", "222", "333", "444", "555", "666", "777", "888", "999" |
| 1 | 20 | | ]; |
| | 21 | |
|
| | 22 | | /// <summary> |
| | 23 | | /// Time complexity - O(n) |
| | 24 | | /// Space complexity - O(1) |
| | 25 | | /// </summary> |
| | 26 | | /// <param name="num"></param> |
| | 27 | | /// <returns></returns> |
| | 28 | | public string LargestGoodInteger(string num) |
| 5 | 29 | | { |
| 5 | 30 | | var maxChar = '\0'; |
| | 31 | |
|
| 56 | 32 | | for (var i = 0; i <= num.Length - 3; i++) |
| 23 | 33 | | { |
| 23 | 34 | | var c = num[i]; |
| | 35 | |
|
| 23 | 36 | | if (c != num[i + 1] || c != num[i + 2] || c <= maxChar) |
| 19 | 37 | | { |
| 19 | 38 | | continue; |
| | 39 | | } |
| | 40 | |
|
| 4 | 41 | | if (c == '9') |
| 0 | 42 | | { |
| 0 | 43 | | return Triples[^1]; |
| | 44 | | } |
| | 45 | |
|
| 4 | 46 | | maxChar = c; |
| 4 | 47 | | } |
| | 48 | |
|
| 5 | 49 | | return maxChar == '\0' ? string.Empty : Triples[maxChar - '0']; |
| 5 | 50 | | } |
| | 51 | | } |