Algorithm

[python] HackerRank - Sherlock and the Valid String

khakhalog 2023. 5. 20. 01:51

문제

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' 가 되는 경우는

  1. 모든 문자가 같은 갯수로 나타날 때 ex) "aabbcc"
  2. 1개 삭제 가능한 경우
    1. 갯수가 다른 문자(대신 갯수가 더 커야함)가 하나 있고, 그 차이가 1일 때 ex) "aaabbcc"
    2. 갯수가 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"