Hackerrank Java Substring Comparisons Solution
1 min read

Hackerrank Java Substring Comparisons Solution

Hackerrank Java Substring Comparisons Solution

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;
    }

Enjoying these posts? Subscribe for more


Adblocker detected! Please consider reading this notice.

We've detected that you are using AdBlock Plus or some other adblocking software which is preventing the page from fully loading.

That's okay. But without advertising-income, we can't keep making this site awesome.

We don't have any banner, Flash, animation, obnoxious sound, or popup ad. We do not implement these annoying types of ads!

We need money to operate the site, and almost all of it comes from our online advertising.

Please add thepoorcoder.com to your ad blocking whitelist or disable your adblocking software.

×