Question:
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.
Analysis:
给出一个“pattern”和一个字符串,判断字符串是否跟pattern一致。
下面给出了几个patter-str的例子。
思路:根据上面给出的几个例子可以得知,单个字符与字符串以一对一的形式出现,而且位置也要对应。因此可以用一个哈希map控制两者的对应。但是HashMap只能保证key值不重复出现,不能保证value不重复。因此还需要额外的一个set来控制String的单一。
Answer:
public class Solution { public boolean wordPattern(String pattern, String str) { Map<Character, String> map = new HashMap<Character, String> (); Set<String> set = new HashSet<String>(); char[] ch = pattern.toCharArray(); String[] strr = str.split(" "); if(ch.length != strr.length) return false; for(int i=0; i<ch.length; i++) { if(!map.containsKey(ch[i]) && !set.contains(strr[i])) { map.put(ch[i], strr[i]); set.add(strr[i]); } else { if(set.contains(strr[i]) && !map.containsKey(ch[i])) return false; if(!map.get(ch[i]).equals(strr[i])) return false; } } return true; } }