-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPatternMatching.java
More file actions
38 lines (35 loc) · 1.22 KB
/
PatternMatching.java
File metadata and controls
38 lines (35 loc) · 1.22 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
package swe.Strings;
import java.util.*;
public class PatternMatching {
public static List<String> findPattern(String[] words, String pattern) {
List<String> output = new ArrayList<>();
for (String word : words) {
if (word.length() != pattern.length()) {
continue;
}
Map<Character, Character> charMap = new HashMap<>();
Boolean isValid = true;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
char p = pattern.charAt(i);
if (!charMap.containsKey(c) && !charMap.containsValue(p)) {
charMap.put(c, p);
} else if (charMap.containsKey(c) && charMap.get(c) == p) {
continue;
} else {
isValid = false;
break;
}
}
if (isValid) {
output.add(word);
}
}
return output;
}
public static void main(String[] args) {
String[] array = {"foo", "bar", "baz", "bat"};
String str = "abb";
System.out.println(findPattern(array,str));
}
}