3403. Find the Lexicographically Largest String From the Box I #1766
-
Topics: You are given a string Alice is organizing a game for her
Find the lexicographically largest1 string from the box after all the rounds are finished. Example 1:
Example 2:
Example 3:
Example 4:
Constraints:
Hint:
Footnotes
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find the lexicographically largest string from a box that contains all possible non-empty substrings obtained by splitting the given string into Approach
Let's implement this solution in PHP: 3403. Find the Lexicographically Largest String From the Box I <?php
/**
* @param String $word
* @param Integer $numFriends
* @return String
*/
function answerString($word, $numFriends) {
$n = strlen($word);
if ($numFriends == 1) {
return $word;
}
$maxLen = $n - $numFriends + 1;
$candidate_start = 0;
$candidate_len = min($maxLen, $n);
for ($i = 1; $i < $n; $i++) {
$len = min($maxLen, $n - $i);
$min_len = min($len, $candidate_len);
$j = 0;
while ($j < $min_len) {
if ($word[$i + $j] != $word[$candidate_start + $j]) {
break;
}
$j++;
}
if ($j < $min_len) {
if ($word[$i + $j] > $word[$candidate_start + $j]) {
$candidate_start = $i;
$candidate_len = $len;
}
} else {
if ($len > $candidate_len) {
$candidate_start = $i;
$candidate_len = $len;
}
}
}
return substr($word, $candidate_start, $candidate_len);
}
// Example Test Cases
// Test Case 1
echo answerString("dbca", 2) . "\n"; // Output: "dbc"
// Test Case 2
echo answerString("gggg", 4) . "\n"; // Output: "g"
// Test Case 3
echo answerString("gh", 1) . "\n"; // Output: "gh"
// Test Case 4
echo answerString("cgwzebexlahnfqsetbeaybmfdzywpvehjybpwiotnciddjonfi", 21) . "\n"; // Output: "zywpvehjybpwiotnciddjonfi"
?> Explanation:
This approach ensures that we efficiently find the lexicographically largest substring by leveraging direct character comparisons and optimal substring length constraints. The algorithm efficiently handles the worst-case scenarios with a time complexity of O(n^2), which is feasible given the problem constraints. |
Beta Was this translation helpful? Give feedback.
We need to find the lexicographically largest string from a box that contains all possible non-empty substrings obtained by splitting the given string into
numFriends
non-empty contiguous parts in all distinct ways. The key insight is recognizing that the lexicographically largest string in the box must be a contiguous substring of the original string with a maximum length ofn - numFriends + 1
, wheren
is the length of the string.Approach
numFriends
is 1, the only possible split is the entire string itself, so we directly return the entire string.