문제
You are given a string s consisting of lowercase letters and an integer k. We call a string t ideal if the following conditions are satisfied:
- t is a subsequence of the string s.
- The absolute difference in the alphabet order of every two adjacent letters in t is less than or equal to k.
Return the length of the longest ideal string.
A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.
Note that the alphabet order is not cyclic. For example, the absolute difference in the alphabet order of 'a' and 'z' is 25, not 1.
문자열 s와 범위 k가 주어졌을 때, 특정 조건을 만족하는 s의 부분문자열 t의 길이의 최대값을 구하는 문제이다.
특정 조건
- t는 s의 부분문자열(substring)이어야 함
- 인접한 문자가 k범위 안에 있어야 함
Example 1:
Input: s = "acfgbd", k = 2
Output: 4
Explanation: The longest ideal string is "acbd". The length of this string is 4, so 4 is returned. Note that "acfgbd" is not ideal because 'c' and 'f' have a difference of 3 in alphabet order.
Example 2:
Input: s = "abcd", k = 3
Output: 4
Explanation: The longest ideal string is "abcd". The length of this string is 4, so 4 is returned.
풀이
아이디어
- s를 앞에서 부터 순회한다.
- 알파벳 별로 최대 길이를 저장해 놓는다.
- 현재 차례의 알파벳의 최대 길이는 k 범위 안에 있는 알바펫 중 최대 길이+1이 된다.
코드
class Solution:
def longestIdealString(self, s: str, k: int) -> int:
# 번호->알파벳 : 0~25 -> a~z
itoc = [chr(i) for i in range(ord('a'), ord('z')+1)]
# 알파벳->번호 : a~z -> 0~25
ctoi = {c: i for i, c in enumerate(itoc)}
# 알파벳 별 최대 길이
cnt = {c: 0 for c in itoc}
for c in s:
# 주변(k범위)에서 가장 긴 길이를 찾아 1을 더한 값을 cnt[c]에 넣어줌
mx = 0
for i in range(k+1):
if ctoi[c]-i >= 0: mx = max([mx, cnt[itoc[ctoi[c]-i]]])
if ctoi[c]+i <= 25: mx = max([mx, cnt[itoc[ctoi[c]+i]]])
cnt[c] = mx+1
mx = 0
for c in itoc:
mx = max([mx, cnt[c]])
return mx
후기
아이디어가 바로 떠오르진 않았지만, 어떤 방식으로 풀어야 할 지 방향성은 잡혔다.
비슷한 문제가 나오더라도 못풀지는 않을 것 같다.
'Algorithm' 카테고리의 다른 글
[LeetCode] 514. Freedom Trail (Daily Question) (0) | 2024.04.27 |
---|---|
[LeetCode] 1289. Minimum Falling Path Sum II (Daily Question) (1) | 2024.04.26 |
[LeetCode] 1137. N-th Tribonacci Number (Daily Question) (0) | 2024.04.24 |
[LeetCode] 310. Minimum Height Trees (Daily Question) (0) | 2024.04.23 |
[LeetCode] 752. Open the Lock (Daily Question) (0) | 2024.04.22 |