Sub-strings of a string that are prefix of the same string
Given a string str, the task is to count all possible sub-strings of the given string that are prefix of the same string.
Examples:
Input: str = “ababc”
Output: 7
All possible sub-string are “a”, “ab”, “aba”, “abab”, “ababc”, “a” and “ab”
Input: str = “abdabc”
Output: 8
Approach: Traverse the string character by character, if the current character is equal to the first character of the string then count all possible sub-strings starting from here that are also the prefixes of str and add it to count. After the complete string has been traversed, print the count.
Below is the implementation of the above approach:
C++14
#include <iostream>
#include <string>
using namespace std;
int subStringsStartingHere(string str, int n,
int startIndex)
{
int count = 0, i = 1;
while (i <= n)
{
if (str.substr(0,i) ==
str.substr(startIndex, i))
{
count++;
}
else
break ;
i++;
}
return count;
}
int countSubStrings(string str, int n)
{
int count = 0;
for ( int i = 0; i < n; i++)
{
if (str[i] == str[0])
count += subStringsStartingHere(str,
n, i);
}
return count;
}
int main()
{
string str = "abcda" ;
int n = str.length();
cout << (countSubStrings(str, n));
}
|
Java
public class GFG
{
public static int subStringsStartingHere(
String str, int n,
int startIndex)
{
int count = 0 , i = startIndex + 1 ;
while (i <= n)
{
if (str.startsWith(str.substring(
startIndex, i)))
{
count++;
}
else
break ;
i++;
}
return count;
}
public static int countSubStrings(String str,
int n)
{
int count = 0 ;
for ( int i = 0 ; i < n; i++)
{
if (str.charAt(i) == str.charAt( 0 ))
count += subStringsStartingHere(str, n, i);
}
return count;
}
public static void main(String[] args)
{
String str = "ababc" ;
int n = str.length();
System.out.println(countSubStrings(str, n));
}
}
|
Python3
def subStringsStartingHere(string, n,
startIndex):
count = 0
i = startIndex + 1
while (i < = n) :
if string.startswith(
string[startIndex : i]):
count + = 1
else :
break
i + = 1
return count
def countSubStrings(string, n) :
count = 0
for i in range (n) :
if string[i] = = string[ 0 ] :
count + = subStringsStartingHere(
string, n, i)
return count
if __name__ = = "__main__" :
string = "ababc"
n = len (string)
print (countSubStrings(string, n))
|
C#
using System;
class GFG
{
static int subStringsStartingHere(
String str, int n,
int startIndex)
{
int count = 0, i = startIndex + 1;
while (i <= n) {
if (str.StartsWith(str.Substring(
startIndex, i-startIndex)))
{
count++;
}
else
break ;
i++;
}
return count;
}
static int countSubStrings(String str, int n)
{
int count = 0;
for ( int i = 0; i < n; i++) {
if (str[i] == str[0])
count += subStringsStartingHere(
str, n, i);
}
return count;
}
static public void Main(String []args)
{
String str = "ababc" ;
int n = str.Length;
Console.WriteLine(countSubStrings(str, n));
}
}
|
Javascript
<script>
function subStringsStartingHere(str, n,
startIndex)
{
var count = 0, i = startIndex + 1;
while (i <= n)
{
if (str.startsWith(
str.substring(startIndex, i)))
{
count++;
}
else
break ;
i++;
}
return count;
}
function countSubStrings(str, n)
{
var count = 0;
for ( var i = 0; i < n; i++)
{
if (str[i] == str[0])
count += subStringsStartingHere(str,
n, i);
}
return count;
}
var str = "abcda" ;
var n = str.length;
document.write(countSubStrings(str, n));
</script>
|
Complexity Analysis:
- Time Complexity: O(N^2)
- Auxiliary Space: O(1)
Efficient Approach:
Prerequisite: Z-Algorithm
Approach: Calculate the z-array of the string such that z[i] stores the length of the longest substring starting from i which is also a prefix of string s. Then to count all possible sub-strings of the string that are prefixes of the same string, we just need to add all the values of the z-array since the total number of substrings matching would be equal to the length of the longest substring.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
vector< int > z_function(string s)
{
int n = ( int )s.length();
vector< int > z(n);
int l = 0, r = 0;
z[0] = n;
for ( int i = 1; i < n; ++i) {
if (i <= r)
z[i] = min(r - i + 1, z[i - l]);
while (i + z[i] < n && s[z[i]] == s[i + z[i]])
++z[i];
if (i + z[i] - 1 > r)
l = i, r = i + z[i] - 1;
}
return z;
}
int main()
{
string s = "abcda" ;
int n = s.length();
vector< int > z = z_function(s);
int count = 0;
for ( auto x : z)
count += x;
cout << count << '\n' ;
return 0;
}
|
Python3
def z_function(s):
n = len (s)
z = [ 0 ] * n
l = 0 ; r = 0
z[ 0 ] = n
for i in range ( 1 , n) :
if (i < = r):
z[i] = min (r - i + 1 , z[i - l])
while (i + z[i] < n and s[z[i]] = = s[i + z[i]]):
z[i] + = 1
if (i + z[i] - 1 > r):
l = i; r = i + z[i] - 1
return z
if __name__ = = '__main__' :
s = "abcda"
n = len (s)
z = z_function(s)
count = 0
for x in z:
count + = x
print (count)
|
C#
using System;
class GFG {
static int [] z_function( string s)
{
int n = s.Length;
int [] z = new int [n];
int l = 0, r = 0;
z[0] = n;
for ( int i = 1; i < n; ++i)
{
if (i <= r)
z[i] = Math.Min(r - i + 1, z[i - l]);
while (i + z[i] < n && s[z[i]] == s[i + z[i]])
++z[i];
if (i + z[i] - 1 > r)
l = i;
r = i + z[i] - 1;
}
return z;
}
public static void Main()
{
string s = "abcda" ;
int n = s.Length;
int [] z = z_function(s);
int count = 0;
for ( int i = 0; i < z.Length; i++)
count += z[i];
Console.WriteLine(count);
}
}
|
Javascript
<script>
function z_function(s)
{
let n = s.length;
let z = new Array(n).fill(0);
let l = 0, r = 0;
z[0] = n;
for (let i = 1; i < n; i++)
{
if (i <= r)
z[i] = Math.min(r - i + 1, z[i - l]);
while (i + z[i] < n && s[z[i]] == s[i + z[i]])
z[i]++;
if (i + z[i] - 1 > r)
l = i, r = i + z[i] - 1;
}
return z;
}
let s = "abcda" ;
let n = s.length;
let z = z_function(s);
let count = 0;
for (let x of z)
count += x;
document.write(count)
</script>
|
Java
import java.util.*;
public class Main {
public static ArrayList<Integer> z_function(String s) {
int n = s.length();
ArrayList<Integer> z = new ArrayList<Integer>(Collections.nCopies(n, 0 ));
int l = 0 , r = 0 ;
z.set( 0 , n);
for ( int i = 1 ; i < n; ++i) {
if (i <= r) {
z.set(i, Math.min(r - i + 1 , z.get(i - l)));
}
while (i + z.get(i) < n && s.charAt(z.get(i)) == s.charAt(i + z.get(i))) {
int value = z.get(i) + 1 ;
z.set(i, value);
}
if (i + z.get(i) - 1 > r) {
l = i;
r = i + z.get(i) - 1 ;
}
}
return z;
}
public static void main(String[] args) {
String s = "abcda" ;
int n = s.length();
ArrayList<Integer> z = z_function(s);
int count = 0 ;
for ( int x : z) {
count += x;
}
System.out.println(count);
}
}
|
Complexity Analysis:
- Time Complexity: O(n)
- Auxiliary Space: O(n)
Last Updated :
20 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...