字符串中子字符串的不同字符集

问题描述

假设一个 SET 是一个字符串中的所有不同字符。 我需要找出由字符串中的子字符串组成的这种不同 SET 的计数。

两个 SETS 中的字符相同时,它们是相同的。

例如:-string=ABBC

answer=6

子串的不同字符集有:{A},{B},{C},{A,B},B,C},{B,C}

注意:子串 BBC 和 BC 有相同的 SET {B,C},ABBC 子串是 SET {A,C}

PS:在hackerearth Augito后端比赛中看到。比赛于30-05-2021结束

约束 1

解决方法

您可以使用双指针方法 + 计算频率。

static int countSub(String str)
{
    int n = (int)str.length();

    // Stores the count of
    // subStrings
    int ans = 0;

    // Stores the frequency
    // of characters
    int []cnt = new int[26];

    // Initialised both pointers
    // to beginning of the String
    int i = 0,j = 0;

    while (i < n)
    {

        // If all characters in
        // subString from index i
        // to j are distinct
        if (j < n &&
        (cnt[str.charAt(j) - 'a'] == 0))
        {

            // Increment count of j-th
            // character
            cnt[str.charAt(j) - 'a']++;

            // Add all subString ending
            // at j and starting at any
            // index between i and j
            // to the answer
            ans += (j - i + 1);

            // Increment 2nd pointer
            j++;
        }

        // If some characters are repeated
        // or j pointer has reached to end
        else
        {

            // Decrement count of j-th
            // character
            cnt[str.charAt(i) - 'a']--;

            // Increment first pointer
            i++;
        }
    }

    // Return the final
    // count of subStrings
    return ans;
}

这里只考虑小写字母。您可以参考here