Largest 3-Same-Digit Number in String

In this problem, you need to find substrings of length 3 in the given string, where all the characters are the same. The goal is to find the maximum such substring in terms of numerical value.

Here’s a Python solution using a sliding window approach. We will iterate over the string with a window of size 3 and check if all characters in the window are the same. If they are, we update our answer with the maximum of the current and previous maximums.

1
2
3
4
5
6
7
8
class Solution:
    def largestGoodInteger(self, num: str) -> str:
        n = len(num)
        res = ""
        for i in range(n - 2):
            if num[i] == num[i + 1] == num[i + 2]:
                res = max(res, num[i:i+3])
        return res

In the code above:

  1. n is the length of the input string num.
  2. res is a string variable initialized as an empty string to store the maximum good integer found so far.
  3. We use a for loop to iterate from the start of num to the third last character. For each index i, we take a slice of num from i to i + 3 and check if all the characters in the slice are the same. If they are, we update res as the maximum of res and the current slice.
  4. Finally, we return res, which is the largest good integer found in num. If no good integer is found, res would remain an empty string, and hence, we would return `"".