Java Substring Comparisons-HackerRank Solution

0

Challenge Description:

 

Given a string, S, and an integer,K , complete the function so that it finds the lexicographically smallest and largest substrings of length k

Function Description

Complete the getSmallestAndLargest function in the editor below.
getSmallestAndLargest has the following parameters:

    string s: a string
    int k: the length of the substrings to find

Returns

  •     string: the string ' + "\n" + ' where and are the two substrings

Input Format

The first line contains a string denoting S.
The second line contains an integer denoting K.

Sample Input 0

 

welcometojava
3

Sample Output 0

ava
wel

Explanation

String s ="welcometojava" has the following lexicographically-ordered substring of length k - 3;


["ava", "com", "elc", "eto", "jav", "lco", "met", "oja", "ome", "toj", "wel"]

We then return the first (lexicographically smallest) substring and the last (lexicographically largest) substring as two newline-separated values (i.e., ava\nwel).

The stub code in the editor then prints ava as our first line of output and wel as our second line of output.

 

Solution

 

import java.util.Scanner;

public class Solution {

    public static String getSmallestAndLargest(String s, int k) {
        String smallest = s.substring(0,k);
        String largest = s.substring(0,k);
        for(int i =0;i<s.length()-k+1;i++)
        {
            String sub = s.substring(i,i+k);
            if(sub.compareTo(smallest)<0){
                smallest = sub;
            }
            if(sub.compareTo(largest)>0) {
                largest = sub;
            }
        }
        
        // Complete the function
        // 'smallest' must be the lexicographically smallest substring of length 'k'
        // 'largest' must be the lexicographically largest substring of length 'k'

        
        return smallest + "\n" + largest;
    }


    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String s = scan.next();
        int k = scan.nextInt();
        scan.close();
      
        System.out.println(getSmallestAndLargest(s, k));
    }

 

Result


 

Explanation

The Java String class compareTo() method compares the given string with the current string lexicographically. It returns a positive number, negative number, or 0.
It compares strings on the basis of the Unicode value of each character in the strings.

If the first string is lexicographically greater than the second string, it returns a positive number (difference of character value). If the first string is less than the second string lexicographically, it returns a negative number, and if the first string is lexicographically equal to the second string, it returns 0.

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment (0)
Our website uses cookies to enhance your experience. Learn More
Accept !