LeetCode 290. Word Pattern (词语模式)

Given a pattern and a string str, find if str follows the same pattern.

Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.

Examples:

  1. pattern = "abba", str = "dog cat cat dog" should return true.
  2. pattern = "abba", str = "dog cat cat fish" should return false.
  3. pattern = "aaaa", str = "dog cat cat dog" should return false.
  4. pattern = "abba", str = "dog dog dog dog" should return false.

 

Notes:
You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.

 


 

题目标签:Hash Table

  题目给了我们一个pattern 和一个 str, 让我们判断,str 是否和 pattern 一致。

  首先,把str split 到 words array 里,如果pattern 的长度 和 words 长度 不一样,直接返回false;

  接下来利用HashMap,把pattern 里的 char 当作key, 每一个word 当作value 存入,如果遇到一样的char,但是有着不一样的value,返回false;如果遇到不一样的char,但有着一样的value,返回false;最后遍历完之后,返回true。

 

 

 

Java Solution:

Runtime beats 36.87% 

完成日期:06/05/2017

关键词:HashMap

关键点:char 当作 key,word 当作 value

 1 class Solution 
 2 {
 3     public boolean wordPattern(String pattern, String str) 
 4     {
 5         HashMap<Character, String> map = new HashMap<>();
 6         
 7         String[] words = str.split(" ");
 8         
 9         if(pattern.length() != words.length)
10             return false;
11         
12         for(int i=0; i<pattern.length(); i++)
13         {
14             char c = pattern.charAt(i);
15 
16             if(map.containsKey(c))
17             {
18                 if(!map.get(c).equals(words[i]))
19                     return false;
20             }
21             else
22             {
23                 if(map.containsValue(words[i]))
24                     return false;
25                 
26                 map.put(c, words[i]);
27             }
28         }
29         
30         return true;
31     }
32 }

参考资料:N/A

 

LeetCode 题目列表 - LeetCode Questions List

转载于:https://www.cnblogs.com/jimmycheng/p/7791491.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值