Contiguous unique substrings with the given length L
Last Updated :
02 Mar, 2023
Given a string str and an integer L. The task is to print all the unique substring of length L from string str.
Examples:
Input: str = “abca”, L=3
Output: “abc”, “bca”
Input: str = “aaaa”, L=3
Output: “aaa”
Approach: Firstly generate all the substring of length L and then by using set we can insert unique sub-string till the length L and then print the result. Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void result(string s, int n)
{
unordered_set<string> st;
for ( int i = 0; i < ( int )s.size(); i++) {
string ans = "" ;
for ( int j = i; j < ( int )s.size(); j++) {
ans += s[j];
if (ans.size() == n) {
st.insert(ans);
break ;
}
}
}
for ( auto it : st)
cout << it << " " ;
}
int main()
{
string s = "abca" ;
int n = 3;
result(s, n);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static void result(String s, int n)
{
HashSet<String> st = new HashSet<String>();
for ( int i = 0 ; i < ( int )s.length(); i++)
{
String ans = "" ;
for ( int j = i; j < ( int )s.length(); j++)
{
ans += s.charAt(j);
if (ans.length()== n)
{
st.add(ans);
break ;
}
}
}
for (String it : st)
System.out.print(it + " " );
}
public static void main(String[] args)
{
String s = "abca" ;
int n = 3 ;
result(s, n);
}
}
|
Python3
def result(s, n) :
st = set ();
for i in range ( len (s)) :
ans = "";
for j in range (i, len (s)) :
ans + = s[j];
if ( len (ans) = = n) :
st.add(ans);
break ;
for it in st :
print (it, end = " " );
if __name__ = = "__main__" :
s = "abca" ;
n = 3 ;
result(s, n);
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static void result(String s, int n)
{
HashSet<String> st = new HashSet<String>();
for ( int i = 0; i < s.Length; i++)
{
String ans = "" ;
for ( int j = i; j < s.Length; j++)
{
ans += s[j];
if (ans.Length == n)
{
st.Add(ans);
break ;
}
}
}
foreach (String it in st)
Console.Write(it + " " );
}
public static void Main(String[] args)
{
String s = "abca" ;
int n = 3;
result(s, n);
}
}
|
Javascript
function result(s, n) {
let st = new Set();
for (let i = 0; i < s.length; i++) {
let ans = "" ;
for (let j = i; j < s.length; j++) {
ans += s[j];
if (ans.length === n) {
st.add(ans);
break ;
}
}
}
for (let it of st) {
process.stdout.write(it + " " );
}
}
let s = "abca" ;
let n = 3;
result(s, n);
|
Share your thoughts in the comments
Please Login to comment...