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.
题意:给定一个模式pattern和一个字符串,判断该字符串是否跟pattern的形式一样。
例:
pattern = "abba", str = "dog cat cat dog" return true.
pattern = "abba", str = "dog cat cat fish" return false.
pattern = "aaaa", str = "dog cat cat dog" return false.
pattern = "abba", str = "dog dog dog dog" return false.
note:
假设pattern中只包含小写字母,字符串str是由空格分割的多个单词组成,且单词也都为小写字母。
思路:使用hashmap
调用put方法时,如果已经存在一个相同的key, 则返回的是前一个key对应的value;如果是新的一个key,则返回的是null
public boolean wordPattern(String pattern, String str) { String[] words = str.split(" "); if(words.length != pattern.length()) return false; Map map = new HashMap(); for(Integer i = 0; i < pattern.length(); i++){ if(map.put(pattern.charAt(i), i) != map.put(words[i], i))//hashmap中, 键可以是任意类型的对象 return false; } return true; }
思路2:把pattern中的每个字符作为key,str中的每个单词作为value
建立pattern中每个字符和str中每个单词的映射关系,且是一对一的映射关系,不能两个key对应相同的value。
在遍历每个字符c时,先判断map中是否存在该字符c,如果存在该字符c,判断该字符c对应的单词(value)是否与此时的单词word[i]相同,若不同,则返回false;
如果map中不存在该字符c,判断该字符c目前对应的单词word[i]是否已经在map中出现过了,若已经存在word[i],则返回false;
如果map中不存在该字符c,且不存在该单词word[i],则将c和word[i]存入map
public boolean wordPattern(String pattern, String str) { String[] words = str.split(" "); if(words.length != pattern.length()) return false; Map<Character, String> map = new HashMap<>(); for(int i = 0; i < words.length; i++){ char c = pattern.charAt(i); if(map.containsKey(c)){ if(!map.get(c).equals(words[i]))//map中已经存在了c,但map中c对应的单词与此时的word[i]不相同 return false; } else{ if(map.containsValue(words[i])){ return false;//map中不存在c,但已经存在了与c相对应的单词 } map.put(c, words[i]); } } return true; }
参考:
https://leetcode.com/problems/word-pattern/discuss/73402/8-lines-simple-Java
https://leetcode.com/problems/word-pattern/discuss/73399/Very-fast-(3ms)-Java-Solution-using-HashMap