Given a string S made of letters a, b and c, find the number of substrings that do not contain all the letters a, b and c. That is the number of sub strings that do not contain at least one of the letters a or b or c.
Note that the sub string should contain at least one letter, that is it should not be the empty string.
Example:
Input: s = "ababa"
Output: 15
Approach
C++
#include <bits/stdc++.h>using namespace std;long long findTheSubstring(string s){long long n = s.size();long long ans = n * (n + 1) / 2;int a = 0, b = 0, c = 0;for (long long i = 0; i < n; i++){if (s[i] == 'a'){a = i + 1;ans -= min(b, c);}else if (s[i] == 'b'){b = i + 1;ans -= min(a, c);}else{c = i + 1;ans -= min(a, b);}}return ans;}int main(){string s = "ababa";cout << findTheSubstring(s) << "\n";return 0;}
No comments:
Post a Comment