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));  
           System.out.println("Smallest subString:-" + list.get(0));  
           System.out.println("Largest subString:-" + list.get(list.size() - 1));  

 Enter the String:-  
 Enter the length  
 Smallest subString:-el  
 Largest subString:-wo  

Enjoy programming.

1 comment:

  1. can you post code that will print the shortest word of a phrase? example "println("i like tacos"); and use a method to take that like and only print i, i being the shortest word.