Java Substring Comparisons

  • + 0 comments

    This can be done without consuming extra space by maintaining an array/list

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