2264. Largest 3-Same-Digit Number in String #2051
-
Topics: You are given a string
Return the maximum good integer as a string or an empty string Note:
Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find the largest 3-digit substring in a given string of digits where all three digits are the same. The solution involves checking for the presence of such substrings in descending order of digit values, from '999' down to '000'. The first substring found in this order will be the largest possible good integer. Approach
Let's implement this solution in PHP: 2264. Largest 3-Same-Digit Number in String <?php
/**
* @param String $num
* @return String
*/
function largestGoodInteger($num) {
for ($digit = 9; $digit >= 0; $digit--) {
$candidate = str_repeat((string)$digit, 3);
if (strpos($num, $candidate) !== false || strpos($num, $candidate) === 0) {
return $candidate;
}
}
return "";
}
// Test cases
echo largestGoodInteger("6777133339") . "\n"; // Output: "777"
echo largestGoodInteger("2300019") . "\n"; // Output: "000"
echo largestGoodInteger("42352338") . "\n"; // Output: ""
?> Explanation:
This approach efficiently locates the largest 3-same-digit substring by leveraging a descending digit iteration and early termination upon finding the first valid candidate. The solution handles edge cases such as leading zeros and absence of any valid substring gracefully. |
Beta Was this translation helpful? Give feedback.
We need to find the largest 3-digit substring in a given string of digits where all three digits are the same. The solution involves checking for the presence of such substrings in descending order of digit values, from '999' down to '000'. The first substring found in this order will be the largest possible good integer.
Approach