-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFaultyKeyboard.java
More file actions
72 lines (65 loc) · 2.49 KB
/
Copy pathFaultyKeyboard.java
File metadata and controls
72 lines (65 loc) · 2.49 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
65
66
67
68
69
70
71
72
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
// https://leetcode.com/discuss/interview-question/643158/google-phone-faulty-keyboard
// https://leetcode.com/discuss/interview-experience/778039/google-phone-interview-rejected
public final class FaultyKeyboard {
static class Trie {
Map<Character, Trie> children = new HashMap<>();
String word;
}
private static void dfs(String s, int i, Trie root, Trie curr,
List<String> path,
List<List<String>> result) {
if (i == s.length()) {
if (curr.word != null) {
path.add(curr.word);
result.add(new ArrayList<>(path));
path.remove(path.size() - 1);
}
return;
}
final char c = s.charAt(i);
if (curr.children.containsKey(c)) {
dfs(s, i + 1, root, curr.children.get(c), path, result);
} else if (c == ' ') {
if (curr.word != null) {
path.add(curr.word);
dfs(s, i + 1, root, root, path, result);
path.remove(path.size() - 1);
}
if (curr.children.containsKey('e')) {
dfs(s, i + 1, root, curr.children.get('e'), path, result);
}
}
}
private static Trie buildTrie(List<String> dict) {
final Trie root = new Trie();
for (String word : dict) {
insert(root, word);
}
return root;
}
private static void insert(Trie root, String word) {
Trie curr = root;
for (char c : word.toCharArray()) {
curr.children.putIfAbsent(c, new Trie());
curr = curr.children.get(c);
}
curr.word = word;
}
private static List<List<String>> faultyKeyboard(String sentence, List<String> dictionary) {
final List<List<String>> result = new ArrayList<>();
final Trie root = buildTrie(dictionary);
dfs(sentence, 0, root, root, new ArrayList<>(), result);
return result;
}
public static void main(String[] args) {
System.out.println(faultyKeyboard("can s r n ",
Arrays.asList("can", "canes", "serene", "rene", "sam")));
System.out.println(faultyKeyboard("I lik to xplor univ rs ",
Arrays.asList("I", "like", "explore", "to", "universe", "rse")));
}
}