-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestCommonPrefix.java
More file actions
49 lines (40 loc) · 1.75 KB
/
LongestCommonPrefix.java
File metadata and controls
49 lines (40 loc) · 1.75 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
import java.util.*;
import java.util.stream.Collectors;
public class LongestCommonPrefix {
public static void main(String[] args) {
String res = longestCommonPrefix( new String[]
{"find", "carmen", "flower", "flow", "flight"} );
System.out.println(res);
}
public static String longestCommonPrefix(String[] strs) {
String prefix = ""; String tmp = "";
// Data preparation
List<String> sortedWords = Arrays.stream(strs).sorted().collect(Collectors.toList());
Map<Character, List<String>> groupedMap = new TreeMap<>();
for (String word : sortedWords) {
char startLetter = word.charAt(0);
groupedMap.putIfAbsent(startLetter, new ArrayList<>());
groupedMap.get(startLetter).add(word);
}
List<List<String>> data = new ArrayList<>(groupedMap.values());
for (List<String> words : data) {
// Find prefix length of the shortest word
int maxWordLen = words.stream().mapToInt(String::length).max().getAsInt();
String maxWord = words.stream().filter(w -> w.length() == maxWordLen)
.collect(Collectors.toList()).get(0);
// Algorithm
for (String word : words) {
String tmpWord = maxWord;
for (int i = maxWord.length() - 1; i > 0; i--) {
if (word.startsWith(tmpWord) && !word.equals(maxWord)) { tmp = tmpWord; }
else { tmpWord = tmpWord.substring(0, i); }
}
}
// Compare prefixes
if (tmp.length() > prefix.length()) {
prefix = tmp;
}
}
return prefix;
}
}