Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- Apache Spark
- 이진탐색
- 티스토리챌린지
- 분산
- Apache Hadoop
- 문자열
- String
- 파이썬
- DP
- 아파치 스파크
- Python
- 아파치 카프카
- heapq
- docker
- 하둡
- 프로그래머스
- 알고리즘
- 아파치 하둡
- 그래프
- leetcode
- 오블완
- 도커
- programmers
- apache kafka
- 카프카
- 우선순위큐
- 분산처리
- BFS
- 리트코드
- 코딩테스트
Archives
- Today
- Total
래원
[LeetCode] 3223. Minimum Length of String After Operations (Python) 본문
알고리즘/LeetCode
[LeetCode] 3223. Minimum Length of String After Operations (Python)
Laewon Jeong 2025. 1. 13. 15:54
난이도: Medium
문제 설명
You are given a string s.
You can perform the following process on s any number of times:
- Choose an index i in the string such that there is at least one character to the left of index i that is equal to s[i], and at least one character to the right that is also equal to s[i].
- Delete the closest character to the left of index i that is equal to s[i].
- Delete the closest character to the right of index i that is equal to s[i].
Return the minimum length of the final string s that you can achieve.
문제 예제
Example 1:
Input: s = "abaacbcbb"
Output: 5
Explanation:
We do the following operations:
- Choose index 2, then remove the characters at indices 0 and 3. The resulting string is s = "bacbcbb".
- Choose index 3, then remove the characters at indices 0 and 5. The resulting string is s = "acbcb".
Example 2:
Input: s = "aa"
Output: 2
Explanation:
We cannot perform any operations, so we return the length of the original string.
제한 사항
- 1 <= s.length <= 2 * 10^5
- s consists only of lowercase English letters.
✏️Solution(솔루션)
class Solution:
def minimumLength(self, s: str) -> int:
count_s = Counter(s)
answer = len(s)
for alpha in count_s:
while count_s[alpha] > 2:
count_s[alpha] -= 2
answer -=2
return answer
먼저, s에 있는 알파벳들의 갯수를 Counter를 통해 저장했다.
문제를 보고 3개 이상의 갯수를 가지는 알파벳들만 뺄 수 있을 거 같았기 때문이다.
저장한 count_s에서 count_s[alpha]가 3이상이라면 3보다 작아질 때까지 -2를 해주었다.
answer 역시 처음 s길이를 저장해놓고 -2를 해주었다.
마지막으로 이 answer를 return하여 정답을 맞출 수 있었다.
풀고 나니 굳이 while문으로 계산할 필요가 없을 것 같았다. 괜히 시간만 더들고...
따라서, 다음과 같이 코드를 수정했고 이 역시 정답을 맞출 수 있었다.
class Solution:
def minimumLength(self, s: str) -> int:
count_s = Counter(s)
answer = len(s)
for alpha in count_s:
if count_s[alpha] > 2:
if count_s[alpha] % 2 == 1:
answer -= (count_s[alpha]) - 1
else:
answer -= (count_s[alpha]) - 2
return answer
문제: 3223. Minimum Length of String After Operations
깃허브: github
'알고리즘 > LeetCode' 카테고리의 다른 글
[LeetCode] 2429. Minimize XOR (Python) (0) | 2025.01.15 |
---|---|
[LeetCode] 2657. Find the Prefix Common Array of Two Arrays (Python) (0) | 2025.01.14 |
[LeetCode] 1400. Construct K Palindrome Strings (Python) (0) | 2025.01.11 |
[LeetCode] 916. Word Subsets (Python) (0) | 2025.01.10 |
[LeetCode] 2185. Counting Words With a Given Prefix (Python) (0) | 2025.01.09 |