You've successfully subscribed to The Poor Coder | Hackerrank Solutions
Great! Next, complete checkout for full access to The Poor Coder | Hackerrank Solutions
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.
Hackerrank Java Substring Comparisons Solution

Hackerrank Java Substring Comparisons Solution

Beeze Aal
Beeze Aal

Solution in java8

Approach 1.

    public static String getSmallestAndLargest(String s, int k) {
        String smallest = s.substring(0, k);
        String largest = s.substring(0, k);
        
        for(int i = 0; i <= s.length() - k; i++){
            String sTemp = s.substring(i, i + k);
            if(sTemp.compareTo(smallest) < 0) {
                smallest = sTemp;
            }
               
            if(sTemp.compareTo(largest) > 0) {
                largest = sTemp;
            } 
        }
        
        return smallest + "\n" + largest;
    }

Approach 2.






  
    public static String getSmallestAndLargest(String s, int k) {
        String smallest = "";
        String largest = "";
        
       
        for(int i = 0;i<=s.length()-k;i++){
             String subString = s.substring(i,i+k);
             if(i == 0){
                 smallest = subString;
             }
             if(subString.compareTo(largest)>0){
                 largest = subString;
             }else if(subString.compareTo(smallest)<0)
                 smallest = subString;
      }
        
        return smallest + "\n" + largest;
    }



Approach 3.


    public static String getSmallestAndLargest(String s, int k) {
        String smallest = "";
        String largest = "";
        
        // Complete the function
        for(int i = 0; i <= s.length() - k; ++i)
        {
            String sub = s.substring(i, i + k);
            if(sub.compareTo(smallest) < 0 || smallest.isEmpty())
            {
                smallest = sub;
            }
            if(sub.compareTo(largest) > 0 || smallest.isEmpty())
            {
                largest = sub;
            }
        }
        
        return smallest + "\n" + largest;
    }