Java Substring Comparisons

  • + 0 comments
    public static String getSmallestAndLargest(String s, int k) {
            String smallest = "";
            String largest = "";
            
            // Complete the function
            // 'smallest' must be the lexicographically smallest substring of length 'k'
            // 'largest' must be the lexicographically largest substring of length 'k'
            String[] a=new String[s.length()-(k-1)];
            largest="\0";
            a[0]=s.substring(0,k); 
            smallest=a[0];
            for(int i=0;i<s.length()-(k-1);i++)
            {
               a[i]=s.substring(i,i+k); 
               if(largest.compareTo(a[i])<0)
               {
                   largest=a[i];
               }
               if(smallest.compareTo(a[i])>0)
               {
                   smallest=a[i];
               }
            }
            return smallest + "\n" + largest;
        }