LeetCode 395. 至少有 K 个重复字符的最长子串

题目描述

395. 至少有 K 个重复字符的最长子串

image-20250420033204622

思路分析

分治法

image-20250508024452631

参考代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
func longestSubstring(s string, k int) int {
	if len(s) == 0 || k > len(s) {
		return 0
	}

	charCount := make(map[byte]int)
	for i := 0; i < len(s); i++ {
		charCount[s[i]]++
	}

	for char, count := range charCount {
		if count < k {
			maxLen := 0
			substrs := strings.Split(s, string(char))
			for _, substr := range substrs {
				maxLen = max(maxLen, longestSubstring(substr, k))
			}
			return maxLen
		}
	}

	return len(s)
}
  • 时间复杂度:O (n * m),其中 n 是字符串的长度,m 是不同字符的数量。
  • 空间复杂度:O (n),用于存储字符出现次数的哈希表和递归调用栈。

➡️ 点击查看 Java 题解

1
write your code here
本文作者:
本文链接: https://hgnulb.github.io/blog/2025/04570603
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!