Smallest Substring

Smallest Substring  

Problem:

The program must accept a string S as the input. The program must print the smallest substring containing all the distinct characters of the string S in it. Note: If more than one such substring is found, print the first occurring substring. 

Boundary Condition(s): 

1 <= Length of string S <= 100 

Input Format: 

The first line contains the value of S. 

Output Format: 

The first line contains the smallest substring with all the distinct characters of the string S. 

Example Input/Output 1: 

Input: 

aabbcccdddd 

Output: 

abbcccd 

Explanation: 

Here the distinct characters are a, b, c and d. The smallest substring with all the characters a, b, c and d is abbcccd. Hence abbcccd is printed as the output. 

Example Input/Output 2: 

Input: 

jsajdnskjd 

Output: 

ajdnsk

Program:

import java.util.*;

public class Hello {

    private static int fun(String str, int a[])

    {

        int al [] = new int [26];

        for(int i=0;i<str.length();i++)

        {

            al[str.charAt(i)-97] = 1;

        }

        for(int i=0;i<26;i++)

        {

            if(a[i] != al[i])

            {

                return 0;

            }

        }

        return 1; 

    }


    public static void main(String[] args)

    {

Scanner sc = new Scanner(System.in); 

String s = sc.next(); 

int a [] = new int [26]; 

for(int i=0;i<s.length();i++)

{

    a[s.charAt(i)-97] = 1;

}

String ans = s; 

for(int i=0;i<s.length();i++)

{

    for(int j=i;j<s.length();j++)

    {

        String sub = s.substring(i,j+1);

        if(fun(sub,a) == 1 && ans.length() > sub.length())

        {

            ans = sub;

        }

    }

}

System.out.print(ans);

}

}

Comments

Popular posts from this blog

Pronic Integers in N - InfyTQ question

Count Strong Points - Accenture

Letters at position of multiples of a number