How to count the number of substrings with exactly k distinct characters in C++

2 Answers

0 votes
#include <iostream>
#include <unordered_map>
 
int CountSubstringWithKDistinctChars(std::string s, int k) {
    int size = s.length();
    int count = 0;
     
    for (int i = 0; i < size; i++) {
        for (int j = i; j < size; j++) {
            int temp = 0;
            std::unordered_map<char,int> um;
            for (int m = i; m <= j; m++) {
                um[s[m]]++;
                 
                if (um[s[m]] == 1) {
                    temp++;
                }
            }
            if (temp == k) {
                count++;
            }
        }
    }
 
   return count;
}
int main(){
   std::string str = "characters";
   int k = 4;
    
   std::cout << "Number of substrings with exactly k distinct characters = "; 
   std::cout << CountSubstringWithKDistinctChars(str, k);
 
}
 
 
 
 
/*
run:
 
Number of substrings with exactly k distinct characters = 9
 
*/

 



answered Sep 17, 2022 by avibootz
edited Sep 18, 2022 by avibootz
0 votes
#include <set>
#include <string>
#include <iostream>

int CountSubstringWithKDistinctChars(const std::string &s, int k) {
	int size = s.length();
    int count = 0;

	for (int i = 0; i < size; i++) {
		char ch = s[i];
		std::string tmp = "";
		tmp += ch;
		std::set<char> st;
		st.insert(ch);

		for (int j = i + 1; j < size; j++) {
			char next_ch = s[j];
			st.insert(next_ch);
			tmp += next_ch;
			
			if (tmp.length() >= k && st.size() == k) {
				count++;
			}
		}
	}

    return count;
}

int main()
{
	std::string str = "characters";
	int k = 4;

	std::cout << CountSubstringWithKDistinctChars(str, k);
}




/*
run:

9

*/

 



answered Sep 18, 2022 by avibootz
...