题目
leetcode.cn/problems/mi… 给你一个长度为
n的字符串word和一个整数k,其中k是n的因数。
在一次操作中,你可以选择任意两个下标 i 和 j,其中 0 <= i, j < n ,且这两个下标都可以被 k 整除,然后用从 j 开始的长度为 k 的子串替换从 i 开始的长度为 k 的子串。也就是说,将子串 word[i..i + k - 1] 替换为子串 word[j..j + k - 1] 。
返回使 word 成为 K 周期字符串 所需的 最少 操作次数。
如果存在某个长度为 k 的字符串 s,使得 word 可以表示为任意次数连接 s ,则称字符串 word 是 K 周期字符串 。例如,如果 word == "ababab",那么 word 就是 s = "ab" 时的 2 周期字符串 。
思路
返回最少的操作次数, 根据题意可知我们找到出现最多次数的子串,然后用 word.length/k - 次数最多的子串即可
代码
public class Solution {
public int minimumOperationsToMakeKPeriodic(String word, int k) {
if (word.length() == k) {
return 0;
}
Map<String, Integer> map = new HashMap<>();
int maxStr = 1;
int index = 0;
while (index < word.length()) {
String substring = word.substring(index, index + k);
if (map.containsKey(substring)) {
Integer count = map.get(substring);
count += 1;
map.put(substring, count);
maxStr = Math.max(maxStr, count);
} else {
map.put(substring, 1);
}
index += k;
}
return word.length() / k - maxStr;
}
}
题解
灵神题解: leetcode.cn/problems/mi…