返回介绍

solution / 1400-1499 / 1415.The k-th Lexicographical String of All Happy Strings of Length n / README_EN

发布于 2024-06-17 01:03:19 字数 4039 浏览 0 评论 0 收藏 0

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

中文文档

Description

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"

 

Constraints:

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

Solutions

Solution 1

class Solution:
  def getHappyString(self, n: int, k: int) -> str:
    def dfs(t):
      if len(t) == n:
        ans.append(t)
        return
      for c in 'abc':
        if t and t[-1] == c:
          continue
        dfs(t + c)

    ans = []
    dfs('')
    return '' if len(ans) < k else ans[k - 1]
class Solution {
  private List<String> ans = new ArrayList<>();

  public String getHappyString(int n, int k) {
    dfs("", n);
    return ans.size() < k ? "" : ans.get(k - 1);
  }

  private void dfs(String t, int n) {
    if (t.length() == n) {
      ans.add(t);
      return;
    }
    for (char c : "abc".toCharArray()) {
      if (t.length() > 0 && t.charAt(t.length() - 1) == c) {
        continue;
      }
      dfs(t + c, n);
    }
  }
}
class Solution {
public:
  vector<string> ans;
  string getHappyString(int n, int k) {
    dfs("", n);
    return ans.size() < k ? "" : ans[k - 1];
  }

  void dfs(string t, int n) {
    if (t.size() == n) {
      ans.push_back(t);
      return;
    }
    for (int c = 'a'; c <= 'c'; ++c) {
      if (t.size() && t.back() == c) continue;
      t.push_back(c);
      dfs(t, n);
      t.pop_back();
    }
  }
};

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文