[LeetCode] 1415. The k-th Lexicographical String of All Happy Strings of Length n (Python)

2025. 2. 19. 14:38·알고리즘/LeetCode

 

 

난이도: 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 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"

 

제한 사항


  • 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

 

'알고리즘 > LeetCode' 카테고리의 다른 글

[LeetCode] 1261. Find Elements in a Contaminated Binary Tree (Python)  (0) 2025.02.21
[LeetCode] 1980. Find Unique Binary String (Python)  (0) 2025.02.20
[LeetCode] 2375. Construct Smallest Number From DI String (Python)  (0) 2025.02.18
[LeetCode] 1079. Letter Tile Possibilities (Python)  (0) 2025.02.17
[LeetCode] 1718. Construct the Lexicographically Largest Valid Sequence (Python)  (0) 2025.02.16
'알고리즘/LeetCode' 카테고리의 다른 글
  • [LeetCode] 1261. Find Elements in a Contaminated Binary Tree (Python)
  • [LeetCode] 1980. Find Unique Binary String (Python)
  • [LeetCode] 2375. Construct Smallest Number From DI String (Python)
  • [LeetCode] 1079. Letter Tile Possibilities (Python)
Laewon Jeong
Laewon Jeong
  • Laewon Jeong
    래원
    Laewon Jeong
    글쓰기 | 관리
  • GitHub

    • github.com/laewonJeong
  • 전체
    오늘
    어제
    • 분류 전체보기 (172)
      • Docker 및 Kubernetes (11)
        • Docker (5)
        • Kubernetes (6)
      • Data Engineering (18)
        • Hadoop (5)
        • Spark (5)
        • Kafka (5)
        • Airflow (3)
      • CI|CD (3)
      • 알고리즘 (136)
        • 알고리즘 (2)
        • LeetCode (118)
        • 프로그래머스 (11)
        • BOJ (1)
        • 코딩테스트 대비 (4)
      • 서버 (2)
        • 미니 서버 (2)
      • 잡담 (1)
  • 태그

    파이썬
    리트코드
    leetcode
    누적합
    BFS
    String
    우선순위큐
    문자열
    티스토리챌린지
    그래프
    Python
    dfs
    분산
    분산처리
    오블완
    Kubernetes
    docker
    아파치 스파크
    programmers
    알고리즘
    코딩테스트
    이진탐색
    도커
    백트래킹
    쿠버네티스
    아파치 하둡
    heapq
    DP
    Apache Spark
    프로그래머스
  • 인기 글

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Laewon Jeong
[LeetCode] 1415. The k-th Lexicographical String of All Happy Strings of Length n (Python)
상단으로

티스토리툴바