对于特定的模式pattern以及特定的字符串str,判断str中的非空单词是否能和pattern中的字符一一对应,注意这里的一一对应是双向的。
示例1:
输入:
“effe”,“good bad bad good”
输出:
true
示例2:
输入:“effe”,“good bad bad not” 输出:false
输入:“efff”,“good bab bad bad bad” 输出:false
解题步骤:先将字符串差分成多个单词,存放至list中
list长度和pattern.length()长度不一致的,首先排除 为false
通过双指针 遍历模式pattern与单词list,每次匹配结果一致 即为true,否则为false
public boolean testMatch(String pattern, String str){
List<StringBuilder> wordList = splitStr(str);
//注意i最大为length()-1
for (int i = 0; i < pattern.length() - 1 ; i++) {
//模式不匹配的话 返回false
if ((pattern.charAt(i) == pattern.charAt(i+1)) != isEquals(wordList, i)){
return false;
}
}
return true;
}
//先将字符串分割为多个单词
private List<StringBuilder> splitStr(String str){
List<StringBuilder> list = new ArrayList<>();
if (str == null || str.length() == 0) return list;
int index = 0;
int length = str.length();
while(index < length){
StringBuilder word = new StringBuilder();
while (index < length && str.charAt(index) != ' '){
word.append(str.charAt(index));
index++;
if (index == length){
break;
}
}
list.add(word);
index++;
}
return list;
}
//查看两个单词是否相等
private boolean isEquals(List<StringBuilder> wordList, int beginIndex){
return wordList.get(beginIndex).toString().equals(wordList.get(beginIndex + 1).toString());
}