-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
b427419
commit e5315b8
Showing
1 changed file
with
42 additions
and
0 deletions.
There are no files selected for viewing
42 changes: 42 additions & 0 deletions
42
Microsoft/Q15NumberofSubstringsContainingAllThre Characters.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
1358. Number of Substrings Containing All Three Characters | ||
// Given a string s consisting only of characters a, b and c. | ||
|
||
// Return the number of substrings containing at least one occurrence of all these characters a, b and c. | ||
// Example 1: | ||
|
||
// Input: s = "abcabc" | ||
// Output: 10 | ||
// Explanation: The substrings containing at least one occurrence of the characters a, b and c are "abc", "abca", "abcab", "abcabc", "bca", "bcab", "bcabc", "cab", "cabc" and "abc" (again). | ||
// Example 2: | ||
|
||
// Input: s = "aaacb" | ||
// Output: 3 | ||
// Explanation: The substrings containing at least one occurrence of the characters a, b and c are "aaacb", "aacb" and "acb". | ||
// Example 3: | ||
|
||
// Input: s = "abc" | ||
// Output: 1 | ||
//Used Sliding Window Approach | ||
|
||
class Solution { | ||
public: | ||
int numberOfSubstrings(string s) { | ||
int left=0, right=0, count=0, n= s.size()-1 ; | ||
unordered_map<char, int> mp ; | ||
|
||
while(right < s.size()){ | ||
mp[s[right]]++ ; | ||
|
||
while(mp['a'] && mp['b'] && mp['c']){ | ||
count += 1+ (n - right) ; | ||
|
||
mp[s[left]]-- ; | ||
left++ ; | ||
} | ||
|
||
right++ ; | ||
} | ||
|
||
return count ; | ||
} | ||
}; |