-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathProblem_2_Index_Pairs_Of_A_String.java
More file actions
57 lines (47 loc) · 1.51 KB
/
Problem_2_Index_Pairs_Of_A_String.java
File metadata and controls
57 lines (47 loc) · 1.51 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
package Trie;
// Problem Statement: Index Pairs of a String (easy)
// LeetCode Question: 1065. Index Pairs of a String
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Problem_2_Index_Pairs_Of_A_String {
class TrieNode {
TrieNode[] children = new TrieNode[26];
boolean isEnd;
public TrieNode(){};
}
class Trie {
TrieNode root = new TrieNode();
public void insert(String word) {
TrieNode cur = root;
for (char c : word.toCharArray()) {
if (cur.children[c - 'a'] == null) {
cur.children[c - 'a'] = new TrieNode();
}
cur = cur.children[c - 'a'];
}
cur.isEnd = true;
}
}
public List<List<Integer>> indexPairs(String text, List<String> words) {
Trie trie = new Trie();
for (String word : words) {
trie.insert(word);
}
List<List<Integer>> result = new ArrayList<>();
for (int i = 0; i < text.length(); i++) {
TrieNode p = trie.root;
for (int j = i; j < text.length(); j++) {
char currentChar = text.charAt(j);
if (p.children[currentChar - 'a'] == null) {
break;
}
p = p.children[currentChar - 'a'];
if (p.isEnd) {
result.add(Arrays.asList(i, j));
}
}
}
return result;
}
}