난이도: Medium
문제 설명
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"
제한 사항
1 <= n <= 10
1 <= k <= 100
✏️ Solution(솔루션)
class Solution:
def getHappyString(self, n: int, k: int) -> str:
cnt = 0
def backtracking(now, s):
nonlocal cnt
if now == n:
cnt += 1
return s if cnt == k else ""
for i in ['a', 'b', 'c']:
if not s or s[-1] != i:
answer = backtracking(now+1, s + i)
if answer:
return answer
return answer
return backtracking(0,'')
먼저 a부터 c까지 탐색하여 가능한 happy string을 만든다.
각 단계에서 만들고 있는 happy string의 이전 알파벳과 새로 추가 할 알파벳이 다른지 확인하고 다음 알파벳으로 넘어갔다.
이렇게 계속 진행하다가 현재 happy string의 길이가 n과 같다고 한다면 cnt를 +1 해주었다.
cnt가 k가 됐을 때, 문제에서 요구하는 happy string이기 때문에 s를 그대로 return 해주었다. cnt가 k가 아닐때는 그냥 빈 문자열을 반환했다.
이렇게 하면 n, k를 만족하는 happy string이 있을 때 알맞는 happy string을 반환할 수 있고, 또 n, k를 만족하는 happy string이 없을 때는 빈 문자열을 반환 할 수 있다.
⚙️ Runtime & Memory
문제: 1415. The k-th Lexicographical String of All Happy Strings of Length n
깃허브: github
algorithmPractice/LeetCode/1516-the-k-th-lexicographical-string-of-all-happy-strings-of-length-n at main · laewonJeong/algorith
하루 한 문제 챌린지. Contribute to laewonJeong/algorithmPractice development by creating an account on GitHub.
github.com