본문 바로가기
파이썬 코딩테스트/해커랭크

HackerRank / Anagram / Python

by S.T.Lee 2021. 12. 31.

https://www.hackerrank.com/challenges/anagram/problem?isFullScreen=true

 

Anagram | HackerRank

Find the minimum number of characters of the first string that we need to change in order to make it an anagram of the second string.

www.hackerrank.com

s가 주어졌을때

s를 이등분하여 anagram이 되게끔 한쪽을 바꿔주면 된다.

단, s의 길이가 홀수이면 무조건 anagram이 될 수 없다.

 

def anagram(s):
    # Write your code here
    if len(s) % 2 == 1:
        return -1
    else:
        left = []
        right = []
        for i in range(len(s)):
            if i <= (len(s)//2)-1:
                left.append(s[i])
            else:
                right.append(s[i])        
        left.sort()
        right.sort()
        if left == right:
            return 0
        else:
            for l in left:
                if l in right:
                    right.remove(l)
            
            return len(right)