题目:
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.
Example 1:
Input: pattern = “abba”, str = “dog cat cat dog”
Output: true
Example 2:
Input:pattern = “abba”, str = “dog cat cat fish”
Output: false
Example 3:
Input: pattern = “aaaa”, str = “dog cat cat dog”
Output: false
Example 4:
Input: pattern = “abba”, str = “dog dog dog dog”
Output: false
Notes:
You may assume pattern contains only lowercase letters, and str contains lowercase letters that may be separated by a single space.
解答:
此题与 LeetCode205(同构字符串) 基本相似,Isomorphic Strings 同构字符串
此题同样采用 hashmap,思路为:
- 将 pattern中 的单个字符作为 hashMap 的 key 值,将 str 中每个单词作为 value 值
- 遍历 pattern 的字符,如果存在于 map 中,要判断对应的value值是否与当前 str 中对应的单词相同。不同则 return false
- 若字符不存在于 map 中,在加入 map 前要先判断当前str中对应的单词作为 value 值是否存在于 map 中,若存在则 return false
class Solution {
public boolean wordPattern(String pattern, String str) {
HashMap<Character,String> map = new HashMap<>();
String[] s = str.split("\\s+");
if(pattern.length()!=s.length) {
return false;
}
for(int i=0;i<pattern.length();i++) {
char ch = pattern.charAt(i);
if(map.containsKey(ch)) {
if(!map.get(ch).equals(s[i])) {
return false;
}
}else {
if(map.containsValue(s[i])) {
return false;
}
map.put(ch,s[i]);
}
}
return true;
}
}
注意:
- 其中上述思路中,第三步尤为重要。在205题中也提到过,因为 pattern 与 str 是双向对应的,即 str 中的单词在 pattern 中也只能有唯一一个字符对应
- hashmap 取值时,要用 equals() 判断是否相等,而不能用 ==
- 注意判断 pattern 和 分隔后的数组 s 长度是否相等。
if(pattern.length()!=s.length)
第一次提交忽略了这种情况,导致错误。
补充: split()
方法
- 此题中,字符串 str 需要依据空格分隔字符串。采用 split()方法,String的 split 方法支持正则表达式。
- 若已知需要处理的字符串首部没有空格,中间每个之间只有一个空格(如本题),可直接采用
String[] s = str.split(" ");
,也可正常分隔字符串。
- 但这种方式不够灵活。当字符串中每个之间存在多个空格时,只有一个空格可被分隔,即多余的空格也会被分隔出来(如上图所示)。则可采用
String[] s = str.split("\\s+");
正则表达式\s表示匹配任何空白字符,+表示匹配一次或多次。
- 若字符串首字母前也存在空格,我们注意到上图字符 a 前方仍有一个空格被保留分隔。因此当首字母前存在空格时,建议先取出首部的字符,再采用 split("\s+") 进行分隔。