LeetCode 2264: Largest 3-Same-Digit Number in String
Problem Description
Explanation:
To solve this problem, we can iterate through all substrings of length 3 in the input string and check if each substring consists of only one unique digit. If it does, we compare it with the current maximum good integer found so far and update it if the current substring is larger.
Algorithm:
- Initialize a variable
maxGood
as an empty string to store the maximum good integer found. - Iterate through all substrings of length 3 in the input string.
- For each substring, check if it consists of only one unique digit.
- If it does, compare it with
maxGood
and updatemaxGood
if the current substring is larger. - Return
maxGood
as the result.
Time Complexity:
- The time complexity of this algorithm is O(n), where n is the length of the input string num.
Space Complexity:
- The space complexity of this algorithm is O(1) as we are using a constant amount of extra space.
:
Solutions
class Solution {
public String findGoodNumber(String num) {
String maxGood = "";
for (int i = 0; i <= num.length() - 3; i++) {
String current = num.substring(i, i + 3);
if (current.charAt(0) == current.charAt(1) && current.charAt(1) == current.charAt(2)) {
if (current.compareTo(maxGood) > 0) {
maxGood = current;
}
}
}
return maxGood;
}
}
Loading editor...