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 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”
生成所有 n 位的 happy stirngs, 然后排序, 取出第 k 个
impl Solution {
fn gen(n: i32) -> Vec<String> {
if n == 1 {
return vec!["a".into(), "b".into(), "c".into()];
}
let prev = Solution::gen(n - 1);
let mut ans = Vec::new();
for p in prev {
match p.chars().last().unwrap() {
'a' => {
let mut b = p.clone();
b.push('b');
ans.push(b);
let mut c = p.clone();
c.push('c');
ans.push(c);
}
'b' => {
let mut a = p.clone();
a.push('a');
ans.push(a);
let mut c = p.clone();
c.push('c');
ans.push(c);
}
_ => {
let mut a = p.clone();
a.push('a');
ans.push(a);
let mut b = p.clone();
b.push('b');
ans.push(b);
}
}
}
ans
}
pub fn get_happy_string(n: i32, k: i32) -> String {
let mut l = Solution::gen(n);
l.sort();
if l.len() < k as usize {
return "".into();
}
l[k as usize - 1].clone()
}
}