We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
  • HackerRank Home

    HackerRank

  • |
  • Prepare
  • Certify
  • Compete
  • Apply
  • Hiring developers?
  1. Prepare
  2. Java
  3. Strings
  4. Java Substring Comparisons
  5. Discussions

Java Substring Comparisons

Problem
Submissions
Leaderboard
Discussions
Editorial

    You are viewing a single comment's thread. Return to all comments →

  • matthewirvine191
    3 months ago+ 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'
            
            int start = 0;
            smallest = s.substring(start, k); //give a starting point of the first 3 characters
            largest = s.substring(start, k);
            while((start + k) <= s.length()){
                
                String Temp = s.substring(start, start+k);
                smallest = (smallest.compareTo(Temp) > 0) ? Temp : smallest;
                largest = (largest.compareTo(Temp) < 0) ? Temp : largest;
                start++;
            }
            
            return smallest + "\n" + largest;
        }
    
    -1|
    Permalink
  • Blog
  • Scoring
  • Environment
  • FAQ
  • About Us
  • Support
  • Careers
  • Terms Of Service
  • Privacy Policy