Tuesday, 8 September 2015

Java Program to Find Lexicographically Smallest and Largest substring of Length K


What is Lexicographic order?

Lexicographic order is an order in which words are displayed in alphabetical order using the appearance of letters in the word.It is also know as dictionary order or alphabetical order.For ex:-"Africa" is smaller than "Bangladesh" ,"He" is smaller than "he".

Sample program:-

 import java.util.ArrayList;  
 import java.util.Collections;  
 import java.util.List;  
 import java.util.Scanner;  
 /**  
  * @author Dixit  
  *   
  */  
 public class LexicographicExample {  
      public static void main(String a[]) {  
           Scanner sc = new Scanner(System.in);  
           System.out.println("Enter the String:-");  
           String str = sc.nextLine();  
           System.out.println("Enter the length");  
           int count = sc.nextInt();  
           List<String> list = new ArrayList<String>();  
           for (int i = 0; i < str.length(); i = i + 1) {  
                if (str.length() - i >= count) {  
                     list.add(str.substring(i, count + i));  
                }  
           }  
           Collections.sort(list);  
           System.out.println("Smallest subString:-" + list.get(0));  
           System.out.println("Largest subString:-" + list.get(list.size() - 1));  
      }  
 }  


 Output  
 Enter the String:-  
 helloworld  
 Enter the length  
 2  
 Smallest subString:-el  
 Largest subString:-wo  


Enjoy programming.

No comments:

Post a Comment