-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathStemInStringArray.java
54 lines (45 loc) · 1.47 KB
/
StemInStringArray.java
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
/*
* Problem https://www.geeksforgeeks.org/longest-common-substring-array-strings/?ref=rp
*/
import java.util.Arrays;
class Stem {
public static String findStem(String[] array) {
if (array == null) {
throw new IllegalArgumentException();
}
if (array.length <= 0) {
return "";
}
// Sort the input array because the stem will be substring of shortest string
Arrays.sort(array);
int n = array.length;
String s = array[0];
int sLength = s.length();
String maxStem = "";
// generate all substrings of s
for (int i = 0; i < sLength; ++i) {
for (int j = i + 1; j <= sLength; ++j) {
String stem = s.substring(i, j);
// Check this stem is substring of all strings in array
int k = 1;
for (k = 1; k < n; ++k) {
if (!array[k].contains(stem)) {
break;
}
}
// Check if this stem is largest
if (k == n && stem.length() > maxStem.length()) {
maxStem = stem;
}
}
}
return maxStem;
}
}
class StemInStringArray {
public static void main(String[] args) {
String[] array = {"grace", "gracefully", "graceful", "disgraceful"};
String stem = Stem.findStem(array);
System.out.println("Stem is : " + stem);
}
}