Java Substring Comparisons

  • + 0 comments

    import java.util.Scanner;

    public class Solution {

    public static String getSmallestAndLargest(String s, int k) {
        String smallest = "";
        String largest = "";
        java.util.List<String> total = new java.util.ArrayList();
    
        // Complete the function
        // 'smallest' must be the lexicographically smallest substring of length 'k'
        // 'largest' must be the lexicographically largest substring of length 'k'
        for(int i=0;i<=s.length()-1;i++)
        {
            try{
            String sort = s.substring(i, k+i);
            total.add(sort); 
            }
            catch(Exception e)
            {
                break;
            }
        }
        java.util.Collections.sort(total);
        smallest = total.get(0);
        largest = total.get(total.size()-1);
    
        return smallest + "\n" + largest;
    }
    
    
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String s = scan.next();
        int k = scan.nextInt();
        scan.close();
    
        System.out.println(getSmallestAndLargest(s, k));
    }
    

    }