Created
February 19, 2025 17:27
-
-
Save tatsuyax25/8542c200f0aae5d72700a9c240c65ddc to your computer and use it in GitHub Desktop.
A happy string is a string that: consists only of letters of the set ['a', 'b', 'c'].
s[i] != s[i + 1] for all values of i from 1 to s.length - 1 (string is 1-indexed).
For example, strings "abc", "ac", "b" and "abcbabcbcb" are all happy strings and
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {number} n | |
* @param {number} k | |
* @return {string} | |
*/ | |
var getHappyString = function(n, k) { | |
// Helper function to perform backtracking and generate all happy string | |
function backtrack(current, result) { | |
// If the current string has reached the desired length, add it to the result list | |
if (current.length === n) { | |
result.push(current); | |
return; | |
} | |
// Iterate through the characters 'a', 'b', 'c' | |
for (let char of ['a', 'b', 'c']) { | |
// Only add the character if it's different from the last character in the current string | |
if (current.length === 0 || current[current.length - 1] !== char) { | |
backtrack(current + char, result); | |
} | |
} | |
} | |
// List to store all happy strings | |
let result = []; | |
// Start backtracking with an empty string | |
backtrack("", result); | |
// If the list has fewer than k happy strings, return an empty string | |
if (result.length < k) { | |
return ""; | |
} | |
// Return the k-th happy string (1-indexed) | |
return result[k - 1]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment