File tree Expand file tree Collapse file tree 2 files changed +39
-0
lines changed
Expand file tree Collapse file tree 2 files changed +39
-0
lines changed Original file line number Diff line number Diff line change 1+ Given a ` pattern ` and a string ` str ` , find if ` str ` follows the same pattern.
2+
3+ Here ** follow** means a full match, such that there is a bijection between a letter in ` pattern ` and a ** non-empty** word in ` str ` .
4+
5+ #####Examples:
6+ 1 . pattern = "abba", str = "dog cat cat dog" should return true.
7+ 2 . pattern = "abba", str = "dog cat cat fish" should return false.
8+ 3 . pattern = "aaaa", str = "dog cat cat dog" should return false.
9+ 4 . pattern = "abba", str = "dog dog dog dog" should return false.
10+ #####Notes:
11+ You may assume ` pattern ` contains only lowercase letters, and ` str ` contains lowercase letters separated by a single space.
Original file line number Diff line number Diff line change 1+ public class Solution {
2+ public boolean wordPattern (String pattern , String str ) {
3+ if (pattern == null || str == null )
4+ return false ;
5+
6+ String [] strs = str .split (" " );
7+
8+ if (pattern .length () != strs .length ) {
9+ return false ;
10+ } else {
11+ Map <String , Character > map1 = new HashMap <String , Character >();
12+ Map <Character , String > map2 = new HashMap <Character , String >();
13+
14+ for (int i = 0 ; i < pattern .length (); i ++) {
15+ if (!map1 .containsKey (strs [i ]) && !map2 .containsKey (pattern .charAt (i ))) {
16+ map1 .put (strs [i ], pattern .charAt (i ));
17+ map2 .put (pattern .charAt (i ), strs [i ]);
18+ } else if (!map1 .containsKey (strs [i ]) || map1 .get (strs [i ]) != pattern .charAt (i )) {
19+ return false ;
20+ } else if (!map2 .containsKey (pattern .charAt (i )) || !strs [i ].equals (map2 .get (pattern .charAt (i )))) {
21+ return false ;
22+ }
23+ }
24+
25+ return true ;
26+ }
27+ }
28+ }
You can’t perform that action at this time.
0 commit comments