1415. The k-th Lexicographical String of All Happy Strings of Length n

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"

Example 4:

Input: n = 2, k = 7
Output: ""

Example 5:

Input: n = 10, k = 100
Output: "abacbabacb"

 

Constraints:

  • 1 <= n <= 10
  • 1 <= k <= 100

思路:长度为n的string对应的个数为3*2^(n-1),然后根据排序取出每位的字符即可,注意 首位区别于其他位

class Solution(object):
    def getHappyString(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: str
        """
        helper = [0] + [3*(2**i) for i in range(n)]

        base = 3*(2**(n-1))//3
        if k > base*3:
            return ''
        elif k > base*2:
            res = ['c']
            k -= base*2
        elif k > base:
            res = ['b']
            k -= base
        else:
            res = ['a']

        for i in range(1, n):
            base = 2**(n-i)//2
            cands = [s for s in ['c','b','a'] if s!=res[-1]]
            if k>base:
                res.append(cands[0])
                k-=base
            else:
                res.append(cands[1])
        return ''.join(res)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值