Different substrings in a string that start and end with given strings
Last Updated :
25 Jul, 2022
Given a string s and two other strings begin and end, find the number of different substrings in the string which begin and end with the given begin and end strings.
Examples:
Input : s = "geeksforgeeks"
begin = "geeks"
end = "for"
Output : 1
Input : s = "vishakha"
begin = "h"
end = "a"
Output : 2
Two different sub-strings are "ha" and "hakha".
Approach: Find all occurrences of string begin and string end. Store the index of each string in two different arrays. After that traverse through the whole string and add one symbol per iteration to already seen sub-strings and map new strings to some non-negative integers. As the ends and beginnings of strings and different strings of equal length are mapped to different numbers (and equal strings are mapped equally), simply count the number of necessary sub-strings of a certain length.
Implementation:
C++
// Cpp program to find number of
// different sub strings
#include <bits/stdc++.h>
using namespace std;
// function to return number of different
// sub-strings
int numberOfDifferentSubstrings(string s, string a,
string b)
{
// initially our answer is zero.
int ans = 0;
// find the length of given strings
int ls = s.size(), la = a.size(), lb = b.size();
// currently make array and initially put zero.
int x[ls] = { 0 }, y[ls] = { 0 };
// find occurrence of "a" and "b" in string "s"
for (int i = 0; i < ls; i++) {
if (s.substr(i, la) == a)
x[i] = 1;
if (s.substr(i, lb) == b)
y[i] = 1;
}
// We use a hash to make sure that same
// substring is not counted twice.
unordered_set<string> hash;
// go through all the positions to find
// occurrence of "a" first.
string curr_substr = "";
for (int i = 0; i < ls; i++) {
// if we found occurrence of "a".
if (x[i]) {
// then go through all the positions
// to find occurrence of "b".
for (int j = i; j < ls; j++) {
// if we do found "b" at index
// j then add it to already
// existed substring.
if (!y[j])
curr_substr += s[j];
// if we found occurrence of "b".
if (y[j]) {
// now add string "b" to
// already existed substring.
curr_substr += s.substr(j, lb);
// If current substring is not
// included already.
if (hash.find(curr_substr) == hash.end())
ans++;
// put any non negative
// integer to make this
// string as already
// existed.
hash.insert(curr_substr);
}
}
// make substring null.
curr_substr = "";
}
}
// return answer.
return ans;
}
// Driver program for above function.
int main()
{
string s = "codecppforfood";
string begin = "c";
string end = "d";
cout << numberOfDifferentSubstrings(s, begin, end)
<< endl;
return 0;
}
Java
// Java program to find number of
// different sub strings
import java.util.HashSet;
class GFG
{
// function to return number of
// different sub-strings
static int numberOfDifferentSubstrings(String s,
char a, char b)
{
// initially our answer is zero.
int ans = 0;
// find the length of given strings
int ls = s.length();
// currently make array and
// initially put zero.
int[] x = new int[ls];
int[] y = new int[ls];
// find occurrence of "a" and "b"
// in string "s"
for (int i = 0; i < ls; i++)
{
if (s.charAt(i) == a)
x[i] = 1;
if (s.charAt(i) == b)
y[i] = 1;
}
// We use a hash to make sure that same
// substring is not counted twice.
HashSet<String> hash = new HashSet<>();
// go through all the positions to find
// occurrence of "a" first.
String curr_substr = "";
for (int i = 0; i < ls; i++)
{
// if we found occurrence of "a".
if (x[i] != 0)
{
// then go through all the positions
// to find occurrence of "b".
for (int j = i; j < ls; j++)
{
// if we do found "b" at index
// j then add it to already
// existed substring.
if (y[j] == 0)
curr_substr += s.charAt(i);
// if we found occurrence of "b".
if (y[j] != 0)
{
// now add string "b" to
// already existed substring.
curr_substr += s.charAt(j);
// If current substring is not
// included already.
if (!hash.contains(curr_substr))
ans++;
// put any non negative
// integer to make this
// string as already
// existed.
hash.add(curr_substr);
}
}
// make substring null.
curr_substr = "";
}
}
// return answer.
return ans;
}
// Driver Code
public static void main(String[] args)
{
String s = "codecppforfood";
char begin = 'c';
char end = 'd';
System.out.println(
numberOfDifferentSubstrings(s, begin, end));
}
}
// This code is contributed by
// sanjeev2552
Python3
# Python 3 program to find number of
# different sub strings
# function to return number of different
# sub-strings
def numberOfDifferentSubstrings(s, a, b):
# initially our answer is zero.
ans = 0
# find the length of given strings
ls = len(s)
la = len(a)
lb = len(b)
# currently make array and initially
# put zero.
x = [0] * ls
y = [0] * ls
# find occurrence of "a" and "b" in string "s"
for i in range(ls):
if (s[i: la + i] == a):
x[i] = 1
if (s[i: lb + i] == b):
y[i] = 1
# We use a hash to make sure that same
# substring is not counted twice.
hash = []
# go through all the positions to find
# occurrence of "a" first.
curr_substr = ""
for i in range(ls):
# if we found occurrence of "a".
if (x[i]):
# then go through all the positions
# to find occurrence of "b".
for j in range( i, ls):
# if we do found "b" at index
# j then add it to already
# existed substring.
if (not y[j]):
curr_substr += s[j]
# if we found occurrence of "b".
if (y[j]):
# now add string "b" to
# already existed substring.
curr_substr += s[j: lb + j]
# If current substring is not
# included already.
if curr_substr not in hash:
ans += 1
# put any non negative integer
# to make this string as already
# existed.
hash.append(curr_substr)
# make substring null.
curr_substr = ""
# return answer.
return ans
# Driver Code
if __name__ == "__main__":
s = "codecppforfood"
begin = "c"
end = "d"
print(numberOfDifferentSubstrings(s, begin, end))
# This code is contributed by ita_c
C#
// C# program to find number of
// different sub strings
using System;
using System.Collections.Generic;
class GFG
{
// function to return number of
// different sub-strings
static int numberOfDifferentSubstrings(String s,
char a, char b)
{
// initially our answer is zero.
int ans = 0;
// find the length of given strings
int ls = s.Length;
// currently make array and
// initially put zero.
int[] x = new int[ls];
int[] y = new int[ls];
// find occurrence of "a" and "b"
// in string "s"
for (int i = 0; i < ls; i++)
{
if (s[i] == a)
x[i] = 1;
if (s[i] == b)
y[i] = 1;
}
// We use a hash to make sure that same
// substring is not counted twice.
HashSet<String> hash = new HashSet<String>();
// go through all the positions to find
// occurrence of "a" first.
String curr_substr = "";
for (int i = 0; i < ls; i++)
{
// if we found occurrence of "a".
if (x[i] != 0)
{
// then go through all the positions
// to find occurrence of "b".
for (int j = i; j < ls; j++)
{
// if we do found "b" at index
// j then add it to already
// existed substring.
if (y[j] == 0)
curr_substr += s[i];
// if we found occurrence of "b".
if (y[j] != 0)
{
// now add string "b" to
// already existed substring.
curr_substr += s[j];
// If current substring is not
// included already.
if (!hash.Contains(curr_substr))
ans++;
// put any non negative
// integer to make this
// string as already
// existed.
hash.Add(curr_substr);
}
}
// make substring null.
curr_substr = "";
}
}
// return answer.
return ans;
}
// Driver Code
public static void Main(String[] args)
{
String s = "codecppforfood";
char begin = 'c';
char end = 'd';
Console.WriteLine(
numberOfDifferentSubstrings(s, begin, end));
}
}
// This code is contributed by Rajput-Ji
JavaScript
<script>
// Javascript program to find number of
// different sub strings
// function to return number of
// different sub-strings
function numberOfDifferentSubstrings(s,a,b)
{
// initially our answer is zero.
let ans = 0;
// find the length of given strings
let ls = s.length;
// currently make array and
// initially put zero.
let x = new Array(ls);
let y = new Array(ls);
for(let i=0;i<ls;i++)
{
x[i]=0;
y[i]=0;
}
// find occurrence of "a" and "b"
// in string "s"
for (let i = 0; i < ls; i++)
{
if (s[i] == a)
x[i] = 1;
if (s[i] == b)
y[i] = 1;
}
// We use a hash to make sure that same
// substring is not counted twice.
let hash = new Set();
// go through all the positions to find
// occurrence of "a" first.
let curr_substr = "";
for (let i = 0; i < ls; i++)
{
// if we found occurrence of "a".
if (x[i] != 0)
{
// then go through all the positions
// to find occurrence of "b".
for (let j = i; j < ls; j++)
{
// if we do found "b" at index
// j then add it to already
// existed substring.
if (y[j] == 0)
curr_substr += s[i];
// if we found occurrence of "b".
if (y[j] != 0)
{
// now add string "b" to
// already existed substring.
curr_substr += s[j];
// If current substring is not
// included already.
if (!hash.has(curr_substr))
ans++;
// put any non negative
// integer to make this
// string as already
// existed.
hash.add(curr_substr);
}
}
// make substring null.
curr_substr = "";
}
}
// return answer.
return ans;
}
// Driver Code
let s = "codecppforfood";
let begin = 'c';
let end = 'd';
document.write(numberOfDifferentSubstrings(s, begin, end));
// This code is contributed by rag2127
</script>
Output:
3
Similar Reads
Find if a string starts and ends with another given string Given a string str and a corner string cs, we need to find out whether the string str starts and ends with the corner string cs or not.Examples: Input : str = "geeksmanishgeeks", cs = "geeks" Output : Yes Input : str = "shreya dhatwalia", cs = "abc" Output : No Algorithm Find length of given string
4 min read
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
10 min read
Find longest substring of S1 that matches in S2 with a given cost Given two strings S1 and S2 of length n. Additionally, two positive integers, target and C. The task is to determine the maximum length of a contiguous substring in S1 such that, by changing any character in the substring of S1 to another character, the resulting substring matches the corresponding
12 min read
Length of longest substring to be deleted to make a string equal to another string Given two strings str1 and str2, where str2 is a subsequence of str1, the task is to find the length of the longest substring of str1 which when removed, makes the strings str2 and str1 equal. Examples: Input: str1 = âprogrammingbloodsâ, str2 = âibloodsâ Output: 8 Explanation: Substrings to be remov
9 min read
Find if a given string can be represented from a substring by iterating the substring ânâ times Given a string 'str', check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. Examples: Input: str = "abcabcabc" Output: true The given string is 3 times repetition of "abc" Input: str = "abadabad" Output: true The given string is 2 times r
15+ min read