forked from super30admin/Hashing-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWordPattern.java
36 lines (32 loc) · 1.13 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
// Time Complexity :O(n)
// Space Complexity :O(n)
// Did this code successfully run on Leetcode :Yes
// Any problem you faced while coding this :
class Solution {
public boolean wordPattern(String pattern, String s) {
if (pattern == null || s == null)
return false;
HashMap<Character, String> pMap = new HashMap<>();
HashMap<String, Character> sMap = new HashMap<>();
String[] wordArray = s.split(" ");
for (int i = 0; i < pattern.length(); i++) {
char patternChar = pattern.charAt(i);
String wordString = wordArray[i].trim();
if (!pMap.containsKey(patternChar)) {
pMap.put(patternChar, wordString);
} else {
if (!pMap.get(patternChar).equals(wordString)) {
return false;
}
}
if (!sMap.containsKey(wordString)) {
sMap.put(wordString, patternChar);
} else {
if (!sMap.get(wordString).equals(patternChar)) {
return false;
}
}
}
return true;
}
}