2264. Largest 3-Same-Digit Number in String
EasyView on LeetCode
Time: O(10 * n)
Space: O(1)
Advertisement
Intuition
Remove leading zeros from non-first digits. For number with k zeros before non-zero: remove k-1 zeros (keep one). Special case: all zeros.
Algorithm
- 1Split by non-zero digits. For each group of zeros between digits: keep exactly one zero.
- 2Or: regex replace leading zeros in each numeric group.
Common Pitfalls
- •First digit cannot be zero. Inner groups can have one zero. Trailing zeros stay.
2264.cs
C#
// Approach: Scan from digit '9' down; return first three-identical-digit substring found.
// Time: O(10 * n) Space: O(1)
public class Solution
{
public string LargestGoodInteger(string num)
{
// Loop backwards from '9' to '0'
// This will ensure that the first good integer found is the largest
for (int i = 9; i >= 0; i--)
{
// Create a string consisting of three identical digits
string tripleDigit = new string(char.Parse(i.ToString()), 3);
// Check if the num string contains the tripleDigit
if (num.Contains(tripleDigit))
// Return the found good integer (since we started from 9, it's the largest)
return tripleDigit;
}
// If no good integer is found, return an empty string
return "";
}
}Advertisement
Was this solution helpful?