注意的是一定要完全匹配上,包括个数。这里我没有使用Hash,,直接扫描对比得到结果
public boolean wordPattern(String pattern, String str) {
boolean result = false;
if (pattern == null) {
return result;
}
char[] chars = pattern.toCharArray();
String[] strs = str.split(" ");
if (chars.length != strs.length) {
return result;
}
for (int i = 0; i < chars.length; i++) {
for (int j = i + 1; j < chars.length; j++) {
if (chars[i] == chars[j]) {
if (!strs[i].equals(strs[j])) {
return result;
}
} else {
if (strs[i].equals(strs[j])) {
return result;
}
}
}
}
result = true;
return result;
}