Skip to content

Commit 7e13665

Browse files
committed
commit
1 parent 3b1997b commit 7e13665

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

290. Word Pattern.java

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
class Solution {
2+
public boolean wordPattern(String pattern, String s) {
3+
String[] words = s.split(" ");
4+
5+
// Base case
6+
if (words.length != pattern.length())
7+
return false;
8+
9+
Map<Character, String> map = new HashMap<>();
10+
11+
for (int i = 0; i < pattern.length(); i++) {
12+
char ch = pattern.charAt(i);
13+
14+
String word = words[i];
15+
16+
// Check if pattern already exists in map
17+
if (!map.containsKey(ch)) {
18+
// But the word already exist
19+
if (map.containsValue(word))
20+
return false;
21+
22+
// Word is not exist
23+
map.put(ch, word);
24+
}
25+
// Check the value with exist pattern
26+
else if (!map.get(ch).equals(word))
27+
return false;
28+
}
29+
30+
return true;
31+
}
32+
}

0 commit comments

Comments
 (0)