I want to order the substring of string 's' lexographically of length 'k'
I have tried to first sort the characters of the string lexographically using comapareTo
function and then have tried to print the first and last substring
public static String getSmallestAndLargest(String s, int k) {
String smallest = "";
String largest = "";
char ch1,ch2,temp;
int i,j,res;
// 'smallest' must be the lexicographically smallest substring of length 'k'
// 'largest' must be the lexicographically largest substring of length 'k'
for(i=0;i<s.length();i++)
{
ch1=s.charAt(i);
for(j=i+1;j<=s.length();j++)
{
ch2=s.charAt(j);
res=ch2.compareTo(ch1);
if(res<0)
{
temp=ch2;
ch2=ch1;
ch1=temp;
}
}
}
smallest=s.substring(0,k);
largest=s.substring(s.length()-k);
return smallest + "\n" + largest;
}
expected output: Return the respective lexicographically smallest and largest substrings as a single newline-separated string.
input: welcometojava
3
expected output:ava
wel