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.
- Prepare
- Java
- Strings
- Java Substring Comparisons
- Discussions
Java Substring Comparisons
Java Substring Comparisons
+ 0 comments Java substring comparisons are as precise as choosing my daily coffee at starbucks my daily. Just like selecting the perfect blend, Java's substring methods allow us to find and compare specific portions of text with precision and ease. It's all about that attention to detail, just like my daily Starbucks order!
+ 0 comments public static String getSmallestAndLargest(String s, int k) { String smallest = ""; String largest = ""; // Complete the function // 'smallest' must be the lexicographically smallest substring of length 'k' // 'largest' must be the lexicographically largest substring of length 'k' String[] a=new String[s.length()-(k-1)]; largest="\0"; a[0]=s.substring(0,k); smallest=a[0]; for(int i=0;i<s.length()-(k-1);i++) { a[i]=s.substring(i,i+k); if(largest.compareTo(a[i])<0) { largest=a[i]; } if(smallest.compareTo(a[i])>0) { smallest=a[i]; } } return smallest + "\n" + largest; }
+ 0 comments public static String getSmallestAndLargest(String s, int k) { String smallest = ""; String largest = ""; // Complete the function // 'smallest' must be the lexicographically smallest substring of length 'k' // 'largest' must be the lexicographically largest substring of length 'k' int start = 0; smallest = s.substring(start, k); //give a starting point of the first 3 characters largest = s.substring(start, k); while((start + k) <= s.length()){ String Temp = s.substring(start, start+k); smallest = (smallest.compareTo(Temp) > 0) ? Temp : smallest; largest = (largest.compareTo(Temp) < 0) ? Temp : largest; start++; } return smallest + "\n" + largest; }
+ 0 comments public static String getSmallestAndLargest(String s, int k) { java.util.SortedSet<String> set = new java.util.TreeSet<String>(); int len = s.length() - k; for(int i = 0; i<=len;i++){ set.add(s.substring(i, i+k)); } return set.first() + "\n" + set.last(); }
+ 1 comment public static String getSmallestAndLargest(String s, int k) { String smallest = ""; String largest = ""; String[] subStr = new String[s.length() - (k-1)]; subStr[0] = s.substring(0,k); // adding all substrings to a array for(int i = 1; i < subStr.length; i++) { subStr[i] = s.substring(i,i + k); } // using bubble sort for lexicographically element order for(int i = 0; i < subStr.length; i++) { for(int j = 0; j < subStr.length - i - 1; j++) { if(subStr[j].compareTo(subStr[j + 1]) > 0) { String temp = subStr[j]; subStr[j] = subStr[j + 1]; subStr[j + 1] = temp; } } } smallest = subStr[0]; largest = subStr[subStr.length - 1]; return smallest + "\n" + largest; }
Load more conversations
Sort 1566 Discussions, By:
Please Login in order to post a comment