Java Substring Comparisons

  • + 0 comments

    Perfectly working, Logic is just that you need to keep checking all the substrings untill compateTo() function filters all the substrings lexographically.

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

    }