반응형
Notice
Recent Posts
Recent Comments
- Today
- Total
작심삼일
[LeetCode] 763 | Partition Labels | Python 본문
728x90
반응형
문제 링크: https://leetcode.com/problems/partition-labels/
문제
You are given a string s. We want to partition the string into as many parts as possible so that each letter appears in at most one part.
Note that the partition is done so that after concatenating all the parts in order, the resultant string should be s.
Return a list of integers representing the size of these parts.
조건
- 1 <= s.length <= 500
- s consists of lowercase English letters.
내 풀이
알파벳이 나오는 index를 count에 저장한다.
s를 앞에서부터 차례로 훑으면서 maxi에 현재의 알파벳이 뒤에 또 나오면, 그 index를 저장한다.
코드
class Solution:
def partitionLabels(self, s: str) -> List[int]:
sList = list(s)
count = [[] for _ in range(26)]
ans = []
for idx, char in enumerate(sList):
count[ord(char) - ord('a')].append(idx)
maxi = 0
for idx, char in enumerate(sList):
alphabet = ord(char) - ord('a')
del count[alphabet][0]
if len(count[alphabet]):
maxi = max(maxi, count[alphabet][0])
if maxi == idx:
if len(ans) == 0:
ans.append(maxi+1)
else:
ans.append(maxi-sum(ans)+1)
maxi = idx+1
if maxi-sum(ans)+1 > 0:
ans.append(maxi-sum(ans)+1)
return ans[:-1]
728x90
반응형
'스터디 > 코테' 카테고리의 다른 글
[LeetCode] 991 | Broken Calculator | Python (0) | 2022.03.23 |
---|---|
[LeetCode] 1663 | Smallest String With A Given Numeric Value | Python (0) | 2022.03.22 |
[LeetCode] 316 | Remove Duplicate Letters | Python (0) | 2022.03.18 |
[LeetCode] 856 | Score of Parentheses | Python (0) | 2022.03.17 |
[LeetCode] 946 | Validate Stack Sequences | Python (0) | 2022.03.16 |
Comments