Skip to content

Commit 0e52e02

Browse files
committed
Add solution #1415
1 parent f5c04d0 commit 0e52e02

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -463,6 +463,7 @@
463463
1402|[Reducing Dishes](./1402-reducing-dishes.js)|Hard|
464464
1408|[String Matching in an Array](./1408-string-matching-in-an-array.js)|Easy|
465465
1410|[HTML Entity Parser](./1410-html-entity-parser.js)|Medium|
466+
1415|[The k-th Lexicographical String of All Happy Strings of Length n](./1415-the-k-th-lexicographical-string-of-all-happy-strings-of-length-n.js)|Medium|
466467
1431|[Kids With the Greatest Number of Candies](./1431-kids-with-the-greatest-number-of-candies.js)|Easy|
467468
1436|[Destination City](./1436-destination-city.js)|Easy|
468469
1437|[Check If All 1's Are at Least Length K Places Away](./1437-check-if-all-1s-are-at-least-length-k-places-away.js)|Easy|
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/**
2+
* 1415. The k-th Lexicographical String of All Happy Strings of Length n
3+
* https://leetcode.com/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/
4+
* Difficulty: Medium
5+
*
6+
* A happy string is a string that:
7+
* - consists only of letters of the set ['a', 'b', 'c'].
8+
* - s[i] != s[i + 1] for all values of i from 1 to s.length - 1 (string is 1-indexed).
9+
*
10+
* For example, strings "abc", "ac", "b" and "abcbabcbcb" are all happy strings and strings "aa",
11+
* "baa" and "ababbc" are not happy strings.
12+
*
13+
* Given two integers n and k, consider a list of all happy strings of length n sorted in
14+
* lexicographical order.
15+
*
16+
* Return the kth string of this list or return an empty string if there are less than k happy
17+
* strings of length n.
18+
*/
19+
20+
/**
21+
* @param {number} n
22+
* @param {number} k
23+
* @return {string}
24+
*/
25+
var getHappyString = function(n, k) {
26+
return backtrack('') || '';
27+
28+
function backtrack(str) {
29+
if (str.length === n) {
30+
return --k ? false : str;
31+
}
32+
for (const character of 'abc') {
33+
if (character === str[str.length - 1]) {
34+
continue;
35+
}
36+
const value = backtrack(str + character);
37+
if (value) {
38+
return value;
39+
}
40+
}
41+
42+
return false;
43+
}
44+
};

0 commit comments

Comments
 (0)