Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save abhinit21/a8f66269082f85646aec9e2545d7a0a4 to your computer and use it in GitHub Desktop.
Save abhinit21/a8f66269082f85646aec9e2545d7a0a4 to your computer and use it in GitHub Desktop.
Hackerrank Java Substring Comparisons
import java.util.Scanner;
public class Solution {
public static String getSmallestAndLargest(String s, int k) {
String smallest = "";
String largest = "";
smallest = largest = s.substring(0,k);
// "Compare to" method doesn't turn just the equel case it also turns a value.
for(int i=0; i<=s.length()-k+1; i++ ){
String str = s.substring(i,k+i);
if (smallest.compareTo(str)>0){
smallest = str;
}
if(largest.compareTo(str)<0){
largest=str;
}
}
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));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment