import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @param k int整型
* @param t string字符串
* @return int整型
*/
public int maxCount (String s, int k, String t) {
// write code here
int n = s.length();
int maxCount = 0;
for (int i = 0; i <= n - k; ++i) {
String sub = s.substring(i, i + k);
int count = 0;
for (char c : t.toCharArray()) {
count += countOccurrences(sub, c);
}
maxCount = Math.max(maxCount, count);
}
return maxCount;
}
private int countOccurrences(String str, char target) {
int count = 0;
for (char c : str.toCharArray()) {
if (c == target) {
count++;
}
}
return count;
}
}
Java代码
这道题主要考察以下知识点:
- 字符串操作
- 循环和迭代
- 逻辑判断
下面是代码的文字解释:
- 定义了一个名为 maxCount 的函数,接受输入参数 s(字符串)、k(子字符串长度)和 t(目标字符串)。
- 使用一个循环来遍历从索引 0 到 n - k 的范围,以便获取每个长度为 k 的子字符串。
- 在每个子字符串中,创建一个变量 count,用于记录目标字符在子字符串中出现的次数。
- 遍历目标字符串 t 中的每个字符,使用辅助函数 countOccurrences 来计算它在子字符串中出现的次数。
- 通过比较当前的 count 和 maxCount 的值,更新 maxCount 以保留最大的出现次数。
- maxCount 将存储在所有子字符串中可能的最大出现次数。
- 辅助函数 countOccurrences 用于计算字符在子字符串中出现的次数。遍历子字符串的每个字符,如果字符与目标字符匹配,则增加计数。

京公网安备 11010502036488号