Java Substring Comparisons

  • + 0 comments

    public static String getSmallestAndLargest(String s, int k) { int length = s.length(); // initialize with the first substring String smallest = s.substring(0, k); String largest = s.substring(0, k);

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