Skip to content

Commit ecad092

Browse files
solves word pattern
1 parent 3201c57 commit ecad092

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@
8888
| 276 | [Paint Fence](https://leetcode.com/problems/paint-fence) | Easy | |
8989
| 278 | [First Bad Version](https://leetcode.com/problems/first-bad-version) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)]([![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)]) |
9090
| 283 | [Move Zeroes](https://leetcode.com/problems/move-zeroes) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](https://github.com/anishLearnsToCode/leetcode-algorithms/blob/master/src/MoveZeros.java) |
91-
| 290 | [Word Pattern](https://leetcode.com/problems/word-pattern) | Easy | |
91+
| 290 | [Word Pattern](https://leetcode.com/problems/word-pattern) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)]() |
9292
| 292 | [Nim Game](https://leetcode.com/problems/nim-game) | Easy | |
9393
| 293 | [Flip Game](https://leetcode.com/problems/flip-game) | Easy | |
9494
| 299 | [Bulls and Cows](https://leetcode.com/problems/bulls-and-cows) | Easy | |

src/WordPattern.java

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import java.util.HashMap;
2+
import java.util.HashSet;
3+
import java.util.Map;
4+
import java.util.Set;
5+
6+
public class WordPattern {
7+
public static boolean wordPattern(String pattern, String string) {
8+
Map<Character, String> bijection = new HashMap<>();
9+
Set<String> wordsMappedTo = new HashSet<>();
10+
String[] words = string.split(" ");
11+
if (words.length != pattern.length()) {
12+
return false;
13+
}
14+
15+
for (int index = 0 ; index < pattern.length() ; index++) {
16+
char letter = pattern.charAt(index);
17+
String word = words[index];
18+
19+
if (!bijection.getOrDefault(letter, word).equals(word) ||
20+
(!bijection.containsKey(letter) && wordsMappedTo.contains(word))) {
21+
return false;
22+
}
23+
24+
bijection.put(letter, word);
25+
wordsMappedTo.add(word);
26+
}
27+
28+
return true;
29+
}
30+
}

0 commit comments

Comments
 (0)