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.
一刷
题解:本来以为用character->string会很容易求解,但是怎么解决多个character对应同一个string的问题呢。再加个set
class Solution {
public boolean wordPattern(String pattern, String str) {
Map<Character, String> map = new HashMap<>();
Set<String> set = new HashSet<>();
str = str.trim();
String[] strings = str.split(" ");
if(pattern.length()!=strings.length) return false;
for(int i=0; i<strings.length; i++){
char ch = pattern.charAt(i);
if(map.containsKey(ch)){
if(!strings[i].equals(map.get(ch))) return false;
}else{
if(set.contains(strings[i])) return false;
map.put(ch, strings[i]);
set.add(strings[i]);
}
}
return true;
}
}
方法2:
map: String->Integer(index)
如果pattern和string对应的index不同,false
且注意,map.put的返回值为value. 如果map在此时更新,那么返回的是原先的value, 并更新为现在的value; 即第一次更新返回的是null.
于是,if(map.put(String.valueOf(pattern.charAt(i))) !=map.put(strs[i], i)) return false;;
可以使它们满足一一对应的关系。
如何解决input:
"abc"
"b c a"
这样会造成string和pattern的conflict
于是在构造map的时候不制定map的类型,可以同时用character和string作为key
class Solution {
public boolean wordPattern(String pattern, String str) {
String[] words = str.split(" ");
if (words.length != pattern.length())
return false;
Map index = new HashMap();
for (Integer i=0; i<words.length; ++i)
if (index.put(pattern.charAt(i), i) != index.put(words[i], i))
return false;
return true;
}
}