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.
/Adding every subStrings into Array, and then sort it back.
In the end, we can retrieve the smallest and largest subStrings.
Easy and efficient way to read and write./
public static String getSmallestAndLargest(String s, int k) {
String smallest = "";
String largest = "";
/*s.length()-k+1
* this is a formula used to get the number of all possible
* subStrings from a String*/
String[] arr = new String[s.length()-k+1];
for (int i = 0; i < s.length()-(k-1); i++) {
arr[i] = s.substring(i,i+k);
}
Arrays.sort(arr);
smallest = arr[0];
largest = arr[arr.length-1];
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));
}
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Java Substring Comparisons
You are viewing a single comment's thread. Return to all comments →
/Adding every subStrings into Array, and then sort it back. In the end, we can retrieve the smallest and largest subStrings. Easy and efficient way to read and write./
import java.util.Arrays; import java.util.Scanner;
public class Main{
}