pattern
and a string str
, find if str
follows the same pattern.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:
- Both
pattern
andstr
contains only lowercase alphabetical letters. - Both
pattern
andstr
do not have leading or trailing spaces. - Each word in
str
is separated by a single space. - Each letter in
pattern
must map to a word with length that is at least 1.
Credits:
Special thanks to @minglotus6 for adding this problem and creating all test cases.
public class Solution {
public boolean wordPattern(String pattern, String str) {
if (pattern == null || str == null || pattern.length() == 0 || str.length() == 0) {
return false;
}
String tokens[] = str.split(" ");
if (pattern.length() != tokens.length) return false;
HashMap<Character, String> map1 = new HashMap<Character, String>();
HashSet<String> set = new HashSet<String>();
for (int i = 0; i < pattern.length(); i++) {
char c = pattern.charAt(i);
if (map1.containsKey(c)) {
if (!map1.get(c).equals(tokens[i])) {
return false;
}
} else {
if (set.contains(tokens[i])) {
return false;
}
map1.put(c, tokens[i]);
set.add(tokens[i]);
}
}
return true;
}
}
没有评论:
发表评论