-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJavaSubStringComparison.java
More file actions
64 lines (47 loc) · 1.5 KB
/
Copy pathJavaSubStringComparison.java
File metadata and controls
64 lines (47 loc) · 1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/*
Question:
Given a string s and an integer k, find the lexicographically
smallest and largest substrings of length k.
Example:
Input:
welcometojava
3
Output:
ava
wel
*/
import java.util.Scanner;
public class Solution {
public static String getSmallestAndLargest(String s, int k) {
// Initialize smallest and largest with the first substring
String smallest = s.substring(0, k);
String largest = s.substring(0, k);
// Loop through all possible substrings of length k
for (int i = 1; i <= s.length() - k; i++) {
// Get current substring of length k
String c = s.substring(i, i + k);
// Update smallest if current substring is smaller
if (c.compareTo(smallest) < 0) {
smallest = c;
}
// Update largest if current substring is larger
if (c.compareTo(largest) > 0) {
largest = c;
}
}
// Return smallest and largest substrings separated by a new line
return smallest + "\n" + largest;
}
public static void main(String[] args) {
// Create Scanner object to take input
Scanner scan = new Scanner(System.in);
// Read the input string
String s = scan.next();
// Read the value of k
int k = scan.nextInt();
// Close Scanner
scan.close();
// Print the smallest and largest substrings
System.out.println(getSmallestAndLargest(s, k));
}
}