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.
public boolean wordPattern1(String pattern, String str) {
String[] strings = str.split(" ");
if (pattern.length() != strings.length) {
return false;
}
Map<Character, String> mapCharToString = new HashMap<>();
Map<String, Character> mapStringToChar = new HashMap<>();
int i = 0;
for (i = 0; i < pattern.length(); i++) {
// 字符--》字符串的映射
if (mapCharToString.containsKey(pattern.charAt(i))
&& !mapCharToString.get(pattern.charAt(i)).equals(strings[i])) {
return false;
// 字符串----》字符的映射
} else if (mapStringToChar.containsKey(strings[i])
&& !mapStringToChar.get(strings[i]).equals(pattern.charAt(i))) {
return false;
} else {
mapCharToString.put(pattern.charAt(i), strings[i]);
mapStringToChar.put(strings[i], pattern.charAt(i));
}
}
return true;
}