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:
- pattern =
"abba"
, str ="dog cat cat dog"
should return true. - pattern =
"abba"
, str ="dog cat cat fish"
should return false. - pattern =
"aaaa"
, str ="dog cat cat dog"
should return false. - 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