Count of sub-strings that contain character X at least once
Given a string str and a character X. The task is to find the total number of sub-strings that contain the character X at least once.
Examples:
Input: str = “abcd”, X = ‘b’
Output: 6
“ab”, “abc”, “abcd”, “b”, “bc” and “bcd” are the required sub-strings.
Input: str = “geeksforgeeks”, X = ‘e’
Output: 66
Approach: Total number of sub-strings are n * (n + 1) / 2, among them only those sub-strings need to be counted which contain character X. Character X is present in those sub-strings from position of X to the length of the string. For each character before X this sub-string must be counted.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countSubStr(string str, int n, char x)
{
int res = 0, count = 0;
for ( int i = 0; i < n; i++) {
if (str[i] == x) {
res += ((count + 1) * (n - i));
count = 0;
}
else
count++;
}
return res;
}
int main()
{
string str = "abcabc" ;
int n = str.length();
char x = 'c' ;
cout << countSubStr(str, n, x);
return 0;
}
|
Java
class GFG
{
static int countSubStr(String str, int n, char x)
{
int res = 0 , count = 0 ;
for ( int i = 0 ; i < n; i++)
{
if (str.charAt(i) == x)
{
res += ((count + 1 ) * (n - i));
count = 0 ;
}
else
count++;
}
return res;
}
public static void main(String[] args)
{
String str = "abcabc" ;
int n = str.length();
char x = 'c' ;
System.out.println(countSubStr(str, n, x));
}
}
|
Python3
def countSubStr( str , n, x):
res = 0 ; count = 0 ;
for i in range (n):
if ( str [i] = = x):
res + = ((count + 1 ) * (n - i));
count = 0 ;
else :
count + = 1 ;
return res;
str = "abcabc" ;
n = len ( str );
x = 'c' ;
print (countSubStr( str , n, x));
|
C#
using System;
class GFG
{
static int countSubStr(String str, int n, char x)
{
int res = 0, count = 0;
for ( int i = 0; i < n; i++)
{
if (str[i] == x)
{
res += ((count + 1) * (n - i));
count = 0;
}
else
count++;
}
return res;
}
public static void Main(String[] args)
{
String str = "abcabc" ;
int n = str.Length;
char x = 'c' ;
Console.WriteLine(countSubStr(str, n, x));
}
}
|
PHP
<?php
function countSubStr( $str , $n , $x )
{
$res = 0; $count = 0;
for ( $i = 0; $i < $n ; $i ++)
{
if ( $str [ $i ] == $x )
{
$res += (( $count + 1) * ( $n - $i ));
$count = 0;
}
else
$count ++;
}
return $res ;
}
$str = "abcabc" ;
$n = strlen ( $str );
$x = 'c' ;
echo countSubStr( $str , $n , $x );
?>
|
Javascript
<script>
function countSubStr(str, n, x)
{
let res = 0, count = 0;
for (let i = 0; i < n; i++)
{
if (str[i] == x)
{
res += ((count + 1) * (n - i));
count = 0;
}
else
count++;
}
return res;
}
let str = "abcabc" ;
let n = str.length;
let x = 'c' ;
document.write(countSubStr(str, n, x));
</script>
|
Time Complexity: O(N), where N is the length of the given string.
Auxiliary Space: O(1), no extra space required so it is a constant.
Last Updated :
23 May, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...