Sponsored
Sponsored
This approach involves iterating through the string, checking every possible substring of length 3 to see if it consists of the same character. If it does, keep track of the largest such substring found.
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(1), constant space is used.
1using System;
2
3public class Solution {
4 public string LargestGoodInteger(string num) {
5 string maxGood = "";
6 for (int i = 0; i <= num.Length - 3; i++) {
7 if (num[i] == num[i+1] && num[i+1] == num[i+2]) {
8 string curr = num.Substring(i, 3);
9 if (curr.CompareTo(maxGood) > 0) {
10 maxGood = curr;
11 }
12 }
13 }
14 return maxGood;
15 }
16 public static void Main(string[] args) {
17 Solution sol = new Solution();
18 Console.WriteLine(sol.LargestGoodInteger("6777133339"));
19 }
20}
The C# solution similarly inspects each substring triplet, updating the largest good integer when a greater one is found. Use of Substring
and CompareTo
facilitate operations equivalent to those in Java and C++.
This approach builds upon the basic iteration method, with an early termination feature if the maximum possible good integer ("999") is found. This can optimize cases where digits towards the start of the string quickly identify the upper bound, reducing unnecessary checks.
Time Complexity: Less than O(n) in the best case if "999" is early.
Space Complexity: O(1).
1
The optimized C solution works similarly to the brute force solution but includes a check to immediately return "999" once it's encountered because it represents the maximum possible good integer.