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.
// Complete the function
// 'smallest' must be the lexicographically smallest substring of length 'k'
// 'largest' must be the lexicographically largest substring of length 'k'
int num_substrings = s.length() - k + 1;
if (num_substrings < 1)
{
System.out.println("Substring size is too large for the given string.");
//return;
}
//String array
String sub[] = new String[num_substrings];
for(int i=0;i<num_substrings ;i++)
{
//sub[i] = str.substring(start_index,end_index);
sub[i] = s.substring(i, i + k);
}
//Arrays.sort(sub);
// for (String S : sub) {
// System.out.println(S);
// }
//now reordering these substrings according to lexicographical order.
// Bubble sort to sort the substrings lexicographically
for (int i = 0; i < sub.length - 1; i++) {
for (int j = 0; j < sub.length - 1 - i; j++) {
if (sub[j].compareTo(sub[j + 1]) > 0) {
// Swap sub[j] and sub[j + 1]
String temp = sub[j];
sub[j] = sub[j + 1];
sub[j + 1] = temp;
}
}
}
smallest = sub[0];
largest = sub[sub.length-1];
//System.out.println("Smallest substring is: "+ smallest + " " + "largest substring is " + largest );
return smallest + "\n" + largest;
}
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 →
// Complete the function // 'smallest' must be the lexicographically smallest substring of length 'k' // 'largest' must be the lexicographically largest substring of length 'k' int num_substrings = s.length() - k + 1; if (num_substrings < 1) { System.out.println("Substring size is too large for the given string."); //return; }