Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 9488d1e

Browse files
added Substring with Exactly K Distinct Characters
1 parent 0a9d7ca commit 9488d1e

File tree

3 files changed

+48
-0
lines changed

3 files changed

+48
-0
lines changed

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,7 @@ Languages used: Java and Python
130130
- [Minimum Steps to Make Two Strings Anagram](String/MinStepsToMakeTwoStringsAnagram)
131131
- [Rearrange Words in Sentence](String/RearrangeWordsInSentence)
132132
- [String Matching in Array](String/StringMatchingInArray)
133+
- [Substring with Exactly K Distinct Characters](String/SubstrWithExactKDistinctChars)
133134

134135
### [Tree](./Tree)
135136

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Substrings with exactly K distinct chars
2+
3+
[Leetcode Link](https://leetcode.com/discuss/interview-question/370157)
4+
5+
## Problem:
6+
7+
Given a string s and an int k, return an int representing the number of substrings (not unique) of s with exactly k distinct characters. If the given string doesn't have k distinct characters, return 0.
8+
9+
## Example:
10+
11+
```
12+
Input: s = "pqpqs", k = 2
13+
Output: 7
14+
Explanation: ["pq", "pqp", "pqpq", "qp", "qpq", "pq", "qs"]
15+
```
16+
17+
```
18+
Input: s = "aabab", k = 3
19+
Output: 0
20+
```
21+
22+
## Note:
23+
24+
- The input string consists of only lowercase English letters [a-z]
25+
- 0 ≤ k ≤ 26
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
def substrKDistinctChars(s, k):
2+
# result = list()
3+
result = 0
4+
for i in range(len(s)):
5+
distinctChars = set({s[i]})
6+
# subString = s[i]
7+
for j in range(i+1, len(s)):
8+
if len(distinctChars) < k or (len(distinctChars) == k and s[j] in distinctChars):
9+
distinctChars.add(s[j])
10+
# subString += s[j]
11+
else:
12+
break
13+
if len(distinctChars) == k:
14+
# result.append(subString)
15+
result += 1
16+
return result
17+
18+
19+
# test case
20+
s = "pqpqs"
21+
k = 2
22+
print(substrKDistinctChars(s, k))

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /