-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPatternMatching.java
More file actions
112 lines (95 loc) · 2.54 KB
/
PatternMatching.java
File metadata and controls
112 lines (95 loc) · 2.54 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
// Pattern Matching
// Send Feedback
// Given a list of n words and a pattern p that we want to search. Check if the
// pattern p is present the given words or not. Return true if the pattern is
// present and false otherwise.
// Input Format :
// The first line of input contains an integer, that denotes the value of n.
// The following line contains n space-separated words.
// The following line contains a string, that denotes the value of the pattern
// p.
// Output Format :
// The first and only line of output contains true if the pattern is present and
// false otherwise.
// Constraints:
// 0 <= n <= 10^5
// Time Limit: 1 sec
// Sample Input 1 :
// 4
// abc def ghi cba
// de
// Sample Output 1 :
// true
// Sample Input 2 :
// 4
// abc def ghi hg
// hi
// Sample Output 2 :
// true
// Sample Input 3 :
// 4
// abc def ghi hg
// hif
// Sample Output 3 :
// false
import java.util.ArrayList;
import javax.swing.tree.TreeNode;
class TrieNode {
char data;
boolean isTerminating;
TrieNode children[];
int childCount;
public TrieNode(char data) {
this.data = data;
isTerminating = false;
children = new TrieNode[26];
childCount = 0;
}
}
public class Trie {
private TrieNode root;
public int count;
public Trie() {
root = new TrieNode('\0');
}
public boolean search(String word) {
return search(root, word);
}
private boolean search(TrieNode root, String word) {
if (word.length() == 0) {
return true;
}
int childIndex = word.charAt(0) - 'a';
TrieNode child = root.children[childIndex];
if (child == null) {
return false;
}
return search(child, word.substring(1));
}
public void add(String word) {
add(root, word);
}
public void add(TrieNode root, String word) {
if (word.length() == 0) {
root.isTerminating = true;
return;
}
int childIndex = word.charAt(0) - 'a';
TrieNode child = root.children[childIndex];
if (child == null) {
child = new TrieNode(word.charAt(0));
root.children[childIndex] = child;
root.childCount++;
}
add(child, word.substring(1));
}
public boolean patternMatching(ArrayList<String> vect, String pattern) {
// Write your code here
for (String word : vect) {
for (int i = 0; i < word.length(); i++) {
add(word.substring(i));
}
}
return search(pattern);
}
}