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.
public class Solution {
static String getSmallestAndLargest(String s, int k) {
String smallest = s.substring(0,k);
String largest = s.substring(0,k);
for(int i=1;i<=s.length()-k;i++){
String sub = s.substring(i,i+k);
int d = smallest.compareTo(sub);
if(d>0)
smallest = sub;
String new_sub = s.substring(i,i+k);
int p = largest.compareTo(new_sub);
if(p<0)
largest = new_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));
}
}
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 →
import java.util.Scanner;
public class Solution { static String getSmallestAndLargest(String s, int k) { String smallest = s.substring(0,k); String largest = s.substring(0,k); for(int i=1;i<=s.length()-k;i++){ String sub = s.substring(i,i+k); int d = smallest.compareTo(sub); if(d>0) smallest = sub; String new_sub = s.substring(i,i+k); int p = largest.compareTo(new_sub); if(p<0) largest = new_sub;
}