You’re given a string num
representing a large integer. Your task is to return the largest three-digit number that appears in the string num
and is made up of the same digit. If no such number exists, return an empty string.
public class LargestThreeSameDigitNumber {
public static String largestGoodInteger(String num) {
String maxNumber = "";
for (int i = 0; i < num.length() - 2; i++) {
// Get each substring of length 3
String sub = num.substring(i, i + 3);
// Check if all three characters are the same
if (sub.charAt(0) == sub.charAt(1) && sub.charAt(1) == sub.charAt(2)) {
// Update the maxNumber if the current sub is greater
if (sub.compareTo(maxNumber) > 0) {
maxNumber = sub;
}
}
}
return maxNumber;
}
public static void main(String[] args) {
// Test cases
System.out.println(largestGoodInteger("6777133339")); // Should print "777"
System.out.println(largestGoodInteger("2300019")); // Should print "000"
System.out.println(largestGoodInteger("42352338")); // Should print ""
System.out.println(largestGoodInteger("")); // Should print ""
}
}
This solution effectively traverses the input string once and compares fixed-length substrings, ensuring it runs efficiently even for the maximum input size.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?