Count the characters
Given a string S. Count the characters that have ‘N’ number of occurrences. If a character appears consecutively it is counted as 1 occurrence.
Example 1:
Input:
S = "abc", N = 1
Output: 3
Explanation: 'a', 'b' and 'c' all have
1 occurrence.
Example 2:
Input:
S = "codecodefun", N = 2
Output: 4
Explanation: 'c', 'o', 'd' and 'e' have
2 occurrences.
method :
take one h[] array. increment the value in h[] array for all characters in string, now traverse the h[] array and check the value of each character, if it is equal to N than increment c variable.
at the end return c.
c++ implementation :
int getCount (string s, int n) { int h[26]={0}; for(int i=0;i<s.length();i++) { if(s[i]!=s[i-1]) h[s[i]-'a']++; } int c=0; for(int i=0;i<26;i++) { if(h[s[i]-'a']==n) { c++; } } return c; }
time complexity:0(n) where n is the length of the string.
No comments