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.
1public class Solution {
2 public String largestGoodInteger(String num) {
3 String maxGood = "";
4 for (int i = 0; i <= num.length() - 3; i++) {
5 if (num.charAt(i) == num.charAt(i+1) && num.charAt(i+1) == num.charAt(i+2)) {
6 String curr = num.substring(i, i+3);
7 if (curr.compareTo(maxGood) > 0) {
8 maxGood = curr;
9 }
10 }
11 }
12 return maxGood;
13 }
14 public static void main(String[] args) {
15 Solution sol = new Solution();
16 System.out.println(sol.largestGoodInteger("6777133339"));
17 }
18}
In Java, the same logic is applied by using a loop to identify good integers, and then comparing each to find the largest lexicographically. The compareTo
function helps compare substrings directly.
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
public class Solution {
public string LargestGoodIntegerOptimized(string num) {
string maxGood = "";
for (int i = 0; i <= num.Length - 3; i++) {
if (num[i] == num[i+1] && num[i+1] == num[i+2]) {
if (num[i] == '9') return "999";
string curr = num.Substring(i, 3);
if (curr.CompareTo(maxGood) > 0) {
maxGood = curr;
}
}
}
return maxGood;
}
public static void Main(string[] args) {
Solution sol = new Solution();
Console.WriteLine(sol.LargestGoodIntegerOptimized("798939999"));
}
}
C#'s optimized approach declutters execution where '999' is an early answer, thus experimenting with a quick-return case reduces operational times accordingly.