Java Substring Comparisons

  • + 0 comments
    public static String getSmallestAndLargest(String s, int k) {
            String smallest = "";
            String largest = "";
    
            int a = 0, b = 0;
            for (int i=0; i<s.length()-(k-1); i++){
                 String sub = s.substring(i, i+k);
                 a = sub.compareTo(s.substring(a, a+k))>0 ? i : a;
                 b = sub.compareTo(s.substring(b, b+k))<0 ? i : b;
            }
            smallest = s.substring(b, b+k);
            largest = s.substring(a, a+k);
            
            return smallest + "\n" + largest;
        }