K-Substring with K different characters

String

Description

Given a string S and an integer K. Calculate the number of substrings of length K and containing K different characters

Example

String: "abcabc"
K: 3

Answer: 3
substrings:  ["abc", "bca", "cab"]
String: "abacab"
K: 3

Answer: 2
substrings: ["bac", "cab"]

Solution & Analysis

双指针,O(n)时间法度。

i从0开始loop,j也从0开始,但每一个新i的循环,j不返回,继续往前。

用一个HashMap/HashSet来保存当前substring里的字母,找到长度为k且不包含重复字母的substring后,remove i所指的字母,i++,继续寻找。

Sliding Window - Two Pointer

Sliding Window - Two Pointer

Two pointer O(N) create two hashSet, One set to store Character, One Set to store the substring

i start index, test every start index, to check whether it can be a substring of length K and containing different characters if contains duplicate character , break, start from next index

Reference

https://www.jiuzhang.com/solution/k-substring-with-k-different-characters/

Last updated

Was this helpful?