Skip to content

Commit bf94760

Browse files
word pattern
1 parent ac85f2d commit bf94760

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

EASY/src/easy/WordPattern.java

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package easy;
2+
3+
import java.util.HashMap;
4+
import java.util.Map;
5+
6+
public class WordPattern {
7+
8+
public boolean wordPattern(String pattern, String str) {
9+
String[] words = str.split(" ");
10+
char[] patterns = pattern.toCharArray();
11+
Map<Character, String> map = new HashMap();
12+
if(patterns.length != words.length) return false;
13+
for(int i = 0; i < patterns.length; i++){
14+
if(map.containsKey(patterns[i])){
15+
if(!map.get(patterns[i]).equals(words[i])) return false;
16+
} else {
17+
if(map.containsValue(words[i])) return false;//this is for this case: "abba", "dog dog dog dog"
18+
map.put(patterns[i], words[i]);
19+
}
20+
}
21+
return true;
22+
}
23+
24+
}

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
|301|[Remove Invalid Parentheses](https://leetcode.com/problems/remove-invalid-parentheses/)|[Solution]| ? | ? | Hard| BFS
2424
|299|[Bulls and Cows](https://leetcode.com/problems/bulls-and-cows/)|[Solution](../../blob/master/EASY/src/easy/BullsandCows.java)| O(n)|O(1) | Easy|
2525
|292|[Nim Game](https://leetcode.com/problems/nim-game/)|[Solution](../../blob/master/EASY/src/easy/NimGame.java)| O(1)|O(1) | Easy|
26+
|290|[Word Pattern](https://leetcode.com/problems/word-pattern/)|[Solution](../../blob/master/EASY/src/easy/WordPattern.java)| O(n)|O(n) | Easy|
2627
|289|[Game of Life](https://leetcode.com/problems/game-of-life/)|[Solution](../../blob/master/MEDIUM/src/medium/GameOfLife.java)| O(m*n)|O(m*n), could be optimized to O(1) | Medium|
2728
|283|[Move Zeroes](https://leetcode.com/problems/move-zeroes/)|[Solution](../../blob/master/EASY/src/easy/MoveZeroes.java)| O(n)|O(1) | Easy|
2829
|280|[Wiggle Sort](https://leetcode.com/problems/wiggle-sort/)|[Solution](../../blob/master/MEDIUM/src/medium/WiggleSort.java)| O(n)|O(1) | Medium|

0 commit comments

Comments
 (0)