How to find the minimum number of operation(s) to make the string balanced?

后端 未结 5 1648
夕颜
夕颜 2020-12-29 13:27

From Codechef:

A string is considered balanced if and only if all the characters occur in it equal number of times.

You are given a strin

5条回答
  •  情歌与酒
    2020-12-29 13:37

    if __name__ == "__main__":
      for j in range(int(input())):
        S = str(input())
        N = len(S)
        A = [0]*27
        for c in S:
          A[ord(c) - 65] = A[ord(c) - 65] + 1
        A = sorted(A,reverse=True)
        minSwap = N + 1
        for i in range(1,27):
          if N%i == 0:
            temp = N//i
            tempSwap = 0
            for f in range(i):
              if temp > A[f]:
                tempSwap = tempSwap + temp - A[f]
            if tempSwap <= minSwap:
               minSwap = tempSwap
        if minSwap == N+1:
            minSwap = 0
        print(minSwap)
    

提交回复
热议问题