public class Solution {
/**
* @param pattern: a string, denote pattern string
* @param str: a string, denote matching string
* @return: an boolean, denote whether the pattern string and the matching string match or not
*/
public boolean wordPattern(String pattern, String str) {
// write your code here
char[] patterns = pattern.toCharArray();
String[] words = str.split(" ");
Map<Character, String> map = new HashMap<>();
Set<String> set = new HashSet<>();
for (int i = 0; i < patterns.length; i++) {
if (map.containsKey(patterns[i])) {
if (!map.get(patterns[i]).equals(words[i])) {
return false;
}
continue;
}
if (set.contains(words[i])) {
return false;
}
map.put(patterns[i], words[i]);
set.add(words[i]);
}
return true;
}
}