Let's suppose I am given an array; A[] = {1,2,3}
and I want to find all the sub-arrays of this array. The answer should be
{1}
{1,2}
{1,2,3}
{2}
{2,3}
{3}
How to find all possible subarrays of an array efficiently?
Subarray of an array A is A[i..j]
where 0 <= i <= j < n
where n is length of array.
In C language it can be calculated like this:
#include <stdio.h>
int main(){
int A[] = {1,2,3,4,5};
int len=sizeof(A)/sizeof(int);
for( int i=0; i<len; i++ ){
for( int j=i; j<len; j++ ){ // Now A[i..j] is the subarray
for( int k=i; k<=j; k++ )
printf("%d ", A[k]);
printf("\n");
}
}
return 0;
}
We can use substr function to find the all possible sub array.
#include<bits/stdc++.h>
using namespace std;
void generateSubstring(string str)
{
if(str.size()==0)
{
return;
}
else
{
for(int i=0; i<str.size(); i++)
{
for(int j=1; j<=str.size()-i; j++)
{
cout<<str.substr(i, i+j)<<endl;
}
}
}
}
int main()
{
ios::sync_with_stdio(false);
string str;
getline(cin, str);
generateSubstring(str);
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With