determining a substring that is repeated in all of n strings and showing that substring in the output in java

63 Views Asked by At

i want to write a program that first takes the amount of n and then gets n strings (example: if n = 4 it gets 4 strings ) and then checks all the strings and finds the longest substring that contains in all the strings and prints that substring in the output. and also if we have four strings and such substring exists in 3 of them but does not exist in one of them nothing must be printed but if it exists in all 4 of them it must be printed

example1:


input:

3

asdfg


pysdfgjk


sdfgrty

output:

sdfg

example 2:

3

qwesdj

rioqwe

cbnvmnbml

output:


in example 2 qwe is the longest substring that exists in the first and the second word but it does not exist in the third word so nothing must be printed

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        byte n = input.nextByte();

        String[] words = new String[n];

        for ( int i = 0 ; i < n ; i++){

            words[i]=input.next();
        }
    }
}

here i get n as input and also get n strings and store them in an array of strings but i do not know how to determine that substring and how to find out if it exists in the strings or not

1

There are 1 best solutions below

0
Vaibhav Singh On
import java.util.*;

public class Main {
    public static void main(String[] args) {
      Scanner input = new Scanner(System.in);

      byte n = input.nextByte();

      String[] words = new String[n];

      for ( int i = 0 ; i < n ; i++){

          words[i]=input.next();
      }  
      System.out.println(printCommonSubstring(words));
    }
    public static String printCommonSubstring(String[] words){
  
       int count  =0;
  
       String max ="";
  
      for(int i=0;i<words[0].length();i++){
  
        for(int l=i+1;l<=words[0].length();l++){
  
          String sub = words[0].substring(i,l);
          count =0;
     
          for(int j=1; j<words.length;j++){
       
            for(int k=0;k<words[j].length()-sub.length()-1;k++){
          
              if(sub.equals(words[j].substring(k,k+sub.length()))){
                count++;
                break;
              }
            }
          }
      
          if(count== words.length-1 && max.length()<sub.length()){
            max = sub;
          }
        }
      }
      return max;
    }
}

this should work

Any queries -Please comment