灵茶之KMP01

灵茶之KMP01

题目链接

https://codeforces.com/problemset/problem/1137/B

题目大意

输入两个长度均 ≤\(5* 10^5\) 的字符串 s 和字符串 t,只包含 '0' 和 '1'。 重排 s 中的字符,使得 s 中有尽量多的子串等于 t。 输出重排后的 s。 如果有多个答案,输出任意一个。

思路

贪心的思路,每次添加都按照PMT数组中的逻辑添加

题目代码

from collections import Counter
s = input()
cnt = Counter(s)
t = input()
m = len(t)
pmt = [0] * m
c = 0
for i in range(1,m):
    x = t[i]
    while c and t[c] != x:
        c = pmt[c - 1]
    if t[c] == x:
        c += 1
    pmt[i] = c

ans = []
c = 0
for _ in range(len(s)):
    if cnt[t[c]] == 0:
        break
    ans.append(t[c])
    cnt[t[c]] -= 1
    c += 1
    if c == m:
        c = pmt[c - 1]

ans = ''.join(ans) + cnt['0'] * '0' + cnt['1'] * '1'

print(ans)

重大发现

Python的字符串加减次数太多会减慢效率,当要多次添加元素时,尽量先转换成数组,最后再转换成字符串!

posted @ 2024-03-30 16:35  gebeng  阅读(16)  评论(0)    收藏  举报