Find the substrings

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 = 0b = 0c = 0;
    for (long long i = 0i < ni++)
    {
        if (s[i] == 'a')
        {
            a = i + 1;
            ans -= min(bc);
        }
        else if (s[i] == 'b')
        {
            b = i + 1;
            ans -= min(ac);
        }
        else
        {
            c = i + 1;
            ans -= min(ab);
        }
    }
    return ans;
}
int main()
{
    string s = "ababa";

    cout << findTheSubstring(s<< "\n";

    return 0;
}


No comments:

Post a Comment