1405. Longest Happy String #707
-
Topics: A string
Given three integers A substring is a contiguous sequence of characters within a string. Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can employ a greedy algorithm. The approach is based on the following steps:
Let's implement this solution in PHP: 1405. Longest Happy String <?php
/**
* @param Integer $a
* @param Integer $b
* @param Integer $c
* @return String
*/
function longestHappyString($a, $b, $c) {
// Create a max heap to store character counts
$maxHeap = [];
if ($a > 0) $maxHeap[] = ['char' => 'a', 'count' => $a];
if ($b > 0) $maxHeap[] = ['char' => 'b', 'count' => $b];
if ($c > 0) $maxHeap[] = ['char' => 'c', 'count' => $c];
// Sort the heap based on count (max heap)
usort($maxHeap, function($x, $y) {
return $y['count'] - $x['count'];
});
$result = '';
while (count($maxHeap) > 0) {
// Sort the heap to get the character with the highest count
usort($maxHeap, function($x, $y) {
return $y['count'] - $x['count'];
});
// Get the character with the highest count
$first = array_shift($maxHeap); // Most frequent character
if (strlen($result) >= 2 && $result[-1] == $first['char'] && $result[-2] == $first['char']) {
// We can't add this character because it would create 3 in a row
if (count($maxHeap) == 0) break; // No other character to add
// Get the second character
$second = array_shift($maxHeap);
$result .= $second['char'];
$second['count']--;
if ($second['count'] > 0) {
$maxHeap[] = $second; // Add it back if there's more left
}
// Put the first character back
$maxHeap[] = $first; // Add the first character back
} else {
// We can add the first character
$result .= $first['char'];
$first['count']--;
if ($first['count'] > 0) {
$maxHeap[] = $first; // Add it back if there's more left
}
}
}
return $result;
}
// Example usage
$a1 = 1; $b1 = 1; $c1 = 7;
echo "Input: a = $a1, b = $b1, c = $c1\n";
echo "Output: " . longestHappyString($a1, $b1, $c1) . "\n"; // Output: "ccaccbcc" or similar
$a2 = 7; $b2 = 1; $c2 = 0;
echo "Input: a = $a2, b = $b2, c = $c2\n";
echo "Output: " . longestHappyString($a2, $b2, $c2) . "\n"; // Output: "aabaa"
?> Explanation:
Complexity Analysis
This solution efficiently constructs the longest happy string while adhering to the constraints specified in the problem. |
Beta Was this translation helpful? Give feedback.
We can employ a greedy algorithm. The approach is based on the following steps:
Use a Priority Queue (Max Heap):
Construct the String: