360笔试题(子串最多的次数 + 散步)(ac1.64%)
1. 子串出现最多的次数。
解法1:暴力解法通过64,求所有的子串,然后用map来计数。
static void solve() throws IOException {
String line = nextLine();
int count = 0, maxCount = 0;
HashMap<String, Integer> map = new HashMap<>();
for (int i = 1; i <= line.length(); i++) {
for (int j = 0; j < line.length(); j++) {
if (j + i > line.length()) break;
String key = line.substring(j, j+i);
count = map.getOrDefault(key, 0) + 1;
maxCount = Math.max(count, maxCount);
map.put(key, map.getOrDefault(key, 0) + 1);
}
}
System.out.println(maxCount);
} 解法2:巧解:统计字符出现频率即可,ac100%。
static void solve() throws IOException {
String line = nextLine();
int maxCount = 0;
char[] chars = line.toCharArray();
int[] bucket = new int[26];
for (int i = 0 ; i < chars.length; i++) {
bucket[chars[i]-'a'] ++;
maxCount = Math.max(maxCount, bucket[chars[i]-'a']);
}
System.out.println(maxCount);
}
你懂得
腾讯云智研发成长空间 5088人发布