Hackerrank Java Substring Comparisons Solution
Solution in java8
Approach 1.
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; i++){
String sTemp = s.substring(i, i + k);
if(sTemp.compareTo(smallest) < 0) {
smallest = sTemp;
}
if(sTemp.compareTo(largest) > 0) {
largest = sTemp;
}
}
return smallest + "\n" + largest;
}
Approach 2.
public static String getSmallestAndLargest(String s, int k) {
String smallest = "";
String largest = "";
for(int i = 0;i<=s.length()-k;i++){
String subString = s.substring(i,i+k);
if(i == 0){
smallest = subString;
}
if(subString.compareTo(largest)>0){
largest = subString;
}else if(subString.compareTo(smallest)<0)
smallest = subString;
}
return smallest + "\n" + largest;
}
Approach 3.
public static String getSmallestAndLargest(String s, int k) {
String smallest = "";
String largest = "";
// Complete the function
for(int i = 0; i <= s.length() - k; ++i)
{
String sub = s.substring(i, i + k);
if(sub.compareTo(smallest) < 0 || smallest.isEmpty())
{
smallest = sub;
}
if(sub.compareTo(largest) > 0 || smallest.isEmpty())
{
largest = sub;
}
}
return smallest + "\n" + largest;
}