Java Substring Comparisons

  • + 0 comments

    Solution

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