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 ofi
from1
tos.length - 1
(string is 1-indexed).
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 n
and k
, consider a list of all happy strings of length n
sorted in lexicographical order.
Return the kth string of this list or return an empty string if there are less than k
happy strings of length n
.
Example 1:
Input: n = 1, k = 3 Output: "c" Explanation: The list ["a", "b", "c"] contains all happy strings of length 1. The third string is "c".
Example 2:
Input: n = 1, k = 4 Output: "" Explanation: There are only 3 happy strings of length 1.
Example 3:
Input: n = 3, k = 9 Output: "cab" Explanation: There are 12 different happy string of length 3 ["aba", "abc", "aca", "acb", "bab", "bac", "bca", "bcb", "cab", "cac", "cba", "cbc"]. You will find the 9th string = "cab"
Example 4:
Input: n = 2, k = 7 Output: ""
Example 5:
Input: n = 10, k = 100 Output: "abacbabacb"
Constraints:
1 <= n <= 10
1 <= k <= 100
A:
就是实现题。 一个个数呗 (唯一可能tricky的地方就是 需要k--, 来变成 0 based
class Solution { public: string getHappyString(int n, int k) { vector<int> c(n+1,1); for(int j = n-1; j>=0; j--){ c[j] = (j==0?3:2) * c[j+1]; } string res = ""; k--;// zero index if(c[0] <= k){ // since we have k-- above return res; } for(int i =0;i<n;i++){ // find how many next iter count int count = k/c[i+1]; // count can be 0, 1,2 if(i == 0){ res+= ('a'+count); }else{ res += getNext(res.back(), count); } k -= count * c[i+1]; } return res; } private: char getNext(char pre, int count){ // count can only be 0 or 1 if(pre == 'a'){ return count==0? 'b' : 'c'; }else if(pre == 'b'){ return count==0? 'a' : 'c'; }else{// if(pre == 'c'){ return count==0? 'a' : 'b'; } } };
No comments:
Post a Comment