Count substrings made up of a single distinct character
Last Updated :
28 May, 2021
Given a string S of length N, the task is to count the number of substrings made up of a single distinct character.
Note: For the repetitive occurrences of the same substring, count all repetitions.
Examples:
Input: str = “geeksforgeeks”
Output: 15
Explanation: All substrings made up of a single distinct character are {“g”, “e”, “ee”, “e”, “k”, “s”, “f”, “o”, “r”, “g”, “e”, “ee”, “e”, “k”, “s”}.
Input: str = “abaanndscx”
Output: 12
Naive Approach: The simplest approach to solve this problem is to generate all substrings from the given string count the number of substrings that consist of a single distinct character only.
Time Complexity: O(N3)
Auxiliary Space: O(1)
Effective Approach: Follow the steps below to optimize the above approach:
- Initialize a variable, say ans, to store the count of such substrings.
- Iterate over the characters of the string and check if the previous character, say pre, is the same as the current character or not.
- While the previous and current characters are found to be the same, increment subs and add to the answer.
- If the previous and current characters are found to be different, then reinitialize subs to 1.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
void countSubstrings(string s)
{
int ans = 0;
int subs = 1;
char pre = '0' ;
for ( auto & i : s)
{
if (pre == i)
{
subs += 1;
}
else
{
subs = 1;
}
ans += subs;
pre = i;
}
cout << ans <<endl;
}
int main()
{
string s = "geeksforgeeks" ;
countSubstrings(s);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG
{
static void countSubstrings(String s)
{
int ans = 0 ;
int subs = 1 ;
char pre = '0' ;
for ( char i : s.toCharArray())
{
if (pre == i)
{
subs += 1 ;
}
else
{
subs = 1 ;
}
ans += subs;
pre = i;
}
System.out.println(ans);
}
public static void main(String[] args)
{
String s = "geeksforgeeks" ;
countSubstrings(s);
}
}
|
Python3
def countSubstrings(s):
ans = 0
subs = 1
pre = ''
for i in s:
if pre = = i:
subs + = 1
else :
subs = 1
ans + = subs
pre = i
print (ans)
s = 'geeksforgeeks'
countSubstrings(s)
|
C#
using System;
class GFG {
static void countSubstrings( string s)
{
int ans = 0;
int subs = 1;
char pre = '0' ;
foreach ( char i in s)
{
if (pre == i)
{
subs += 1;
}
else
{
subs = 1;
}
ans += subs;
pre = i;
}
Console.WriteLine(ans);
}
static void Main() {
string s = "geeksforgeeks" ;
countSubstrings(s);
}
}
|
Javascript
<script>
function countSubstrings(s)
{
let ans = 0;
let subs = 1;
let pre = '0' ;
for (let i = 0; i < s.length; i++)
{
if (pre == s[i])
{
subs += 1;
}
else
{
subs = 1;
}
ans += subs;
pre = s[i];
}
document.write(ans);
}
let s = "geeksforgeeks" ;
countSubstrings(s);
</script>
|
Time Complexity: O(N)
Auxiliary Space : O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...