The 11th provincial contest python test question G: repeated string

Question G: Repeated string


[Problem description]
If a character string S can be obtained by repeating a certain character string K times, we call S a character string repeating K times. For example, "abcabcabc" can be regarded as "abc" repeated 3 times, so "abcabcabc" is a string repeated 3 times.
In the same way, "aaaaaa" is a string that repeats 2 times, a string that repeats 3 times, and a string that repeats 6 times.
Now, given a string S, can you calculate the minimum number of characters to modify, so that S can become a string of K times?
[Input format] The
first line of input contains an integer K.
The second line contains a string S containing only lowercase letters.
[Output format]
Output an integer to represent the answer. If S cannot be modified to repeat the string K times, 1 is output.
[Sample input]
2
aabbaa
[Sample output]
2

Ideas:

Because he requires a repeated string, len(s)%k!=0 cannot fulfill the above requirements, so output 1. We want to modify S to repeat the string K times, just to find the optimal solution. I can first divide it into k parts to see the characters, which means that the k parts are the same characters.
How to modify characters with minimum?

Insert picture description here
We can determine the optimal solution in the form of a list, first store the column s1+=s[i+i1*m], and change the most repeated characters in the first column to other characters, c+=k- max(x), and then add up the number of modifications to be the optimal solution.

program:

k=int(input())
s=input()
d=[]
x=[]
s1=""
m=len(s)//k
c=0
print(len(s))
if len(s)%k!=0:
     print("1")
else:
     for i in range(m):
          for i1 in range(k):
               s1+=s[i+i1*m]
          d.append(s1)
          s1=""
     for i in d:
          a=set(i)
          for i1 in a:
               x.append(i.count(i1))
          c+=k-max(x)
          x=[]
     print(c)

Reprinting is prohibited. Only for self-study. No responsibility for program errors.

Guess you like

Origin blog.csdn.net/weixin_46640345/article/details/112426954
Recommended