Description

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.

Idea

  • Backtract

Code

class Solution:
    def getHappyString(self, n: int, k: int) -> str:
        ans = ""
        def backtrack(prev):
            nonlocal k, ans
            if ans:
                return
            if len(prev) == n:
                k -= 1
                if k == 0:
                    ans = "".join(prev)
                return
            for c in "abc":
                if prev and prev[-1] == c:
                    continue
                prev.append(c)
                backtrack(prev)
                prev.pop()
        backtrack([])
        return ans