-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWordPatternMatch.java
More file actions
38 lines (28 loc) · 1.14 KB
/
Copy pathWordPatternMatch.java
File metadata and controls
38 lines (28 loc) · 1.14 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
package LeetcodePractice;
import java.util.*;
public class WordPatternMatch {
public boolean wordPattern(String pattern, String s) {
String[] words = s.split(" ");
if (pattern.length() != words.length) return false;
Map<Character, String> charToWord = new HashMap<>();
Map<String, Character> wordToChar = new HashMap<>();
for (int i = 0; i < pattern.length(); i++) {
char ch = pattern.charAt(i);
String word = words[i];
if (charToWord.containsKey(ch)) {
if (!charToWord.get(ch).equals(word)) return false;
} else {
if (wordToChar.containsKey(word)) return false;
charToWord.put(ch, word);
wordToChar.put(word, ch);
}
}
return true;
}
public static void main(String[] args) {
WordPatternMatch obj = new WordPatternMatch();
System.out.println(obj.wordPattern("abba", "dog cat cat dog"));
System.out.println(obj.wordPattern("abba", "dog cat cat fish"));
System.out.println(obj.wordPattern("aaaa", "dog cat cat dog"));
}
}