-
Notifications
You must be signed in to change notification settings - Fork 1
/
WordPattern.java
39 lines (33 loc) · 1.04 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
package com.smlnskgmail.jaman.leetcodejava.easy;
import java.util.HashMap;
import java.util.Map;
// https://leetcode.com/problems/word-pattern/
public class WordPattern {
private final String pattern;
private final String string;
public WordPattern(String pattern, String string) {
this.pattern = pattern;
this.string = string;
}
public boolean solution() {
String[] words = string.split(" ");
if (words.length != pattern.length()) {
return false;
}
Map<Character, String> matches = new HashMap<>();
for (int i = 0; i < pattern.length(); i++) {
char p = pattern.charAt(i);
String word = words[i];
if (matches.containsKey(p)) {
String value = matches.get(p);
if (!value.equals(word)) {
return false;
}
} else if (matches.containsValue(word)) {
return false;
}
matches.put(p, word);
}
return true;
}
}