문제
https://www.hackerrank.com/challenges/sherlock-and-valid-string/problem?isFullScreen=true
Sherlock and the Valid String | HackerRank
Remove some characters from the string such that the new string's characters have the same frequency.
www.hackerrank.com
접근
문자열 문제
defaultdict, set을 이용해서 풀었다.
'YES' 가 되는 경우는
- 모든 문자가 같은 갯수로 나타날 때 ex) "aabbcc"
- 1개 삭제 가능한 경우
- 갯수가 다른 문자(대신 갯수가 더 커야함)가 하나 있고, 그 차이가 1일 때 ex) "aaabbcc"
- 갯수가 1개인 문자가 하나 있고, 나머지 문자들의 갯수는 다 같을 때 ex) "abbbccceee"
코드
from collections import defaultdict
def isValid(s):
dic = defaultdict(int)
for s in s:
dic[s] += 1
values = list(dic.values())
count_set = set(values)
if len(count_set) == 1:
return "YES"
elif len(count_set) == 2:
mx = max(count_set)
mi = min(count_set)
if values.count(mx) == 1 and mx - mi == 1:
return "YES"
if mi == 1 and values.count(mi) == 1:
return "YES"
return "NO"
'Algorithm' 카테고리의 다른 글
[python] HackerRank - Climbing the Leaderboard (0) | 2023.05.18 |
---|---|
[python] 백준 Silver2 1182.부분수열의 합 (0) | 2023.05.13 |
[python] 프로그래머스 level2 구명보트 / 그리디 (0) | 2023.05.12 |
[python] 프로그래머스 level2 큰 수 만들기 / 그리디 (0) | 2023.05.12 |
[python] 프로그래머스 level3 여행경로 / DFS/BFS (1) | 2023.05.11 |