码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Word Pattern

时间:2015-10-23 07:52:00      阅读:380      评论:0      收藏:0      [点我收藏+]

标签:

原题链接在这里:https://leetcode.com/problems/word-pattern/

通过建立HashMap 来存储 character 和 string 之间的对应来检查patter.

但这里要注意需要建立两个HashMap, 既要有character 到 string 的对应也要有string 到 character的对应。

e.g.  "aaaa", str = "dog cat cat dog" should return false. 但是若是没有 char 到 string 的对应就会返回true.

pattern = "abba", str = "dog dog dog dog" should return false. 但是若是没有 string 到 char的对应就会返回true.

 

Note: Character 类 也有一个equals(), 和 String的相同,使用起来也相同。

空格拆分是用的 "\\s+", 这里注意斜杠的方向。

AC Java:

 1 public class Solution {
 2     public boolean wordPattern(String pattern, String str) {
 3         if(pattern == null || pattern.length() == 0){
 4             return false;
 5         }
 6         if(str == null || str.length() == 0){
 7             return false;
 8         }
 9         String [] s = str.split("\\s+");
10         if(pattern.length() != s.length){
11             return false;
12         }
13         //hm1 contains string -> character pair
14         HashMap<String,Character> hm1 = new HashMap<String,Character>();
15         for(int i = 0; i<s.length; i++){
16             if(!hm1.containsKey(s[i])){
17                 hm1.put(s[i],pattern.charAt(i));
18             }else{
19                 if(!hm1.get(s[i]).equals(pattern.charAt(i))){
20                     return false;
21                 }
22             }
23         }
24         //hm2 contains character -> string pair
25         HashMap<Character,String> hm2 = new HashMap<Character,String>();
26         for(int i = 0; i<pattern.length(); i++){
27             if(!hm2.containsKey(pattern.charAt(i))){
28                 hm2.put(pattern.charAt(i),s[i]);
29             }else{
30                 if(!hm2.get(pattern.charAt(i)).equals(s[i])){
31                     return false;
32                 }
33             }
34         }
35         return true;
36     }
37 }

 

LeetCode Word Pattern

标签:

原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/4903352.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!