给定一个模式和一个字符串str,查找str是否遵循相同的模式。
这里遵循的意思是一个完整的匹配,在一个字母的模式和一个非空的单词str之间有一个双向连接的模式对应。
样例
给定模式= "abba", str = "dog cat cat dog",返回true。给定模式= "abba", str = "dog cat cat fish",返回false。
给定模式= "aaaa", str = "dog cat cat dog",返回false。给定模式= "abba", str = "dog dog dog dog",返回false。
解题思路:
类似于Lintcode 638. Isomorphic Strings,建立两个哈希表,双向对应。为建立映射方便,首先将str中的每个单词放进vector中。然后遍历整个patten与words,在依次建立映射的过程中也检验当前映射是否存在与正确,遍历完毕则返回true。
注意一定要建立两个哈希表来映射,以防止abba---“dog dog dog dog”的情况
public class Solution {
/**
* @param pattern: a string, denote pattern string
* @param teststr: 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 teststr) {
// write your code here
char[] patterns = pattern.toCharArray();
String[] strs = teststr.trim().split(" ");
if(patterns.length != strs.length)
return false;
Map<Character, String> map1 = new HashMap<>();
Map<String, Character> map2 = new HashMap<>();
for(int i=0; i<patterns.length; i++){
if(map1.get(patterns[i]) == null && map2.get(strs[i]) == null){
map1.put(patterns[i], strs[i]);
map2.put(strs[i], patterns[i]);
}else if(map1.get(patterns[i]) == null || map2.get(strs[i]) == null)
return false;
else if( !map1.get(patterns[i]).equals(strs[i]) || map2.get(strs[i]) != patterns[i])
return false;
}
return true;
}
}
本文介绍了一种模式匹配算法,该算法通过使用两个哈希表来实现字符串与模式之间的双向映射,确保模式与字符串能够完全匹配。举例说明了如何判断一个给定的字符串是否遵循指定的模式。

被折叠的 条评论
为什么被折叠?



