1415. The k-th Lexicographical String of All Happy Strings of Length n #1334
-
Topics: A happy string is a string that:
For example, strings "abc", "ac", "b" and "abcbabcbcb" are all happy strings and strings "aa", "baa" and "ababbc" are not happy strings. Given two integers Return the kth string of this list or return an empty string if there are less than Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to generate all possible happy strings of a given length Approach
Let's implement this solution in PHP: 1415. The k-th Lexicographical String of All Happy Strings of Length n <?php
/**
* @param Integer $n
* @param Integer $k
* @return String
*/
function getHappyString($n, $k) {
$result = array();
$this->generate("", $n, null, $result);
return (count($result) >= $k) ? $result[$k - 1] : "";
}
/**
* @param $current
* @param $remaining
* @param $last_char
* @param $result
* @return void
*/
function generate($current, $remaining, $last_char, &$result) {
if ($remaining == 0) {
array_push($result, $current);
return;
}
$chars = array('a', 'b', 'c');
foreach ($chars as $c) {
if ($last_char === null || $c != $last_char) {
$this->generate($current . $c, $remaining - 1, $c, $result);
}
}
}
// Test cases
echo getHappyString(1, 3) . "\n"; // Output: "c"
echo getHappyString(1, 4) . "\n"; // Output: ""
echo getHappyString(3, 9) . "\n"; // Output: "cab"
?> Explanation:
This method ensures that we generate all possible happy strings in an optimal manner and leverage the natural lexicographical order of character selection to avoid sorting, resulting in an efficient solution. |
Beta Was this translation helpful? Give feedback.
We need to generate all possible happy strings of a given length
n
and return the k-th string in lexicographical order. A happy string is defined as a string consisting of characters 'a', 'b', and 'c' where no two consecutive characters are the same.Approach
n
. This involves recursively building strings character by character, ensuring that each new character is different from the previous one.k
, return an empty string.