File tree Expand file tree Collapse file tree 3 files changed +63
-0
lines changed Expand file tree Collapse file tree 3 files changed +63
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java .util .HashMap ;
2
+ import java .util .Map ;
3
+
4
+ /**
5
+ * @author: wangjunchao(王俊超)
6
+ * @time: 2018-10-10 17:24
7
+ **/
8
+ public class Solution {
9
+ public boolean wordPattern (String pattern , String str ) {
10
+
11
+ if (pattern == null && str == null ) {
12
+ return true ;
13
+ } else if (pattern == null || str == null ) {
14
+ return false ;
15
+ }
16
+
17
+ String [] parts = str .split ("\\ s+" );
18
+
19
+ if (pattern .length () != parts .length ) {
20
+ return false ;
21
+ }
22
+
23
+ Map <Character , String > map = new HashMap <>();
24
+ Map <String , Character > rmap = new HashMap <>();
25
+
26
+ Character c ;
27
+ for (int i = 0 ; i < pattern .length (); i ++) {
28
+ c = pattern .charAt (i );
29
+ if (!map .containsKey (c )) {
30
+ map .put (c , parts [i ]);
31
+ } else {
32
+ if (!parts [i ].equals (map .get (c ))) {
33
+ return false ;
34
+ }
35
+ }
36
+ // 双射,两边都要验证
37
+ if (!rmap .containsKey (parts [i ])) {
38
+ rmap .put (parts [i ], c );
39
+ } else {
40
+ if (!c .equals (rmap .get (parts [i ]))) {
41
+ return false ;
42
+ }
43
+ }
44
+ }
45
+
46
+ return true ;
47
+ }
48
+ }
Original file line number Diff line number Diff line change
1
+ /**
2
+ * @author: wangjunchao(王俊超)
3
+ * @time: 2018-10-10 17:29
4
+ **/
5
+ public class Test {
6
+ public static void main (String [] args ) {
7
+ Solution solution = new Solution ();
8
+
9
+ System .out .println (solution .wordPattern ("abba" , "dog cat cat dog" ));
10
+ System .out .println (solution .wordPattern ("abba" , "dog cat cat fish" ));
11
+ System .out .println (solution .wordPattern ("aaaa" , "dog cat cat dog" ));
12
+ System .out .println (solution .wordPattern ("abba" , "dog dog dog dog" ));
13
+ }
14
+ }
You can’t perform that action at this time.
0 commit comments