-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWordPattern.java
41 lines (36 loc) · 1.37 KB
/
WordPattern.java
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
import java.util.HashMap;
public class WordPattern {
public static void main(String[] args) {
String pattern = "abab";
String s = "dog cat dog cat";
boolean result = wordPattern(s, pattern);
System.out.println(result);
}
public static boolean wordPattern(String s, String pattern) {
HashMap<String, Character> wordsToPattern = new HashMap<>();
HashMap<Character, String> patternToWords = new HashMap<>();
String[] wordsArray = s.split("\\s+");
if (pattern.length() != wordsArray.length) {
return false;
}
for (int i = 0; i < pattern.length(); i++) {
String currentString = wordsArray[i];
Character currentCharacter = pattern.charAt(i);
if (wordsToPattern.containsKey(currentString)) {
if (wordsToPattern.get(currentString) != currentCharacter) {
return false;
}
} else {
wordsToPattern.put(currentString, currentCharacter);
}
if (patternToWords.containsKey(currentCharacter)) {
if (!patternToWords.get(currentCharacter).equals(currentString)) {
return false;
}
} else {
patternToWords.put(currentCharacter, currentString);
}
}
return true;
}
}