forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0290-word-pattern.java
More file actions
26 lines (21 loc) · 904 Bytes
/
0290-word-pattern.java
File metadata and controls
26 lines (21 loc) · 904 Bytes
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
class Solution {
public boolean wordPattern(String pattern, String s) {
String[] sArray = s.split("\s");
if(sArray.length != pattern.length()) {
return false;
}
HashMap<Character,String> charToWord = new HashMap<>();
HashMap<String,Character> wordToChar = new HashMap<>();
for (int i = 0; i < pattern.length(); i++) {
if(charToWord.containsKey(pattern.charAt(i)) && !charToWord.get(pattern.charAt(i)).equals(sArray[i])) {
return false;
}
if(wordToChar.containsKey(sArray[i]) && !wordToChar.get(sArray[i]).equals(pattern.charAt(i))) {
return false;
}
charToWord.put(pattern.charAt(i),sArray[i]);
wordToChar.put(sArray[i],pattern.charAt(i));
}
return true;
}
}