题目描述:
Given a pattern and a string str, find if str follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.
Example 1:
Input: pattern ="abba", str ="dog cat cat dog"Output: true
Example 2:
Input:pattern ="abba", str ="dog cat cat fish"Output: false
Example 3:
Input: pattern ="aaaa", str ="dog cat cat dog"Output: false
Example 4:
Input: pattern ="abba", str ="dog dog dog dog"Output: false
中文理解:给出两个字符串,其中一个由不含空格的a-z的字符组成为pattern,一个有空格分割组成的字符串s,判断这两个字符是否是相同的模式,相同模式的含义是:pattern的相同字符出现的位置,s中相同位置出现的字符串也要相同。
解题思路:首先HashMap<Character,String> map=new HashMap<Character,String>();使用map来存放pattern中相同字符出现的下标构成字符串,再HashMap<String,String> map1=new HashMap<String,String>();使用map1来存放s中相同字符串出现的下标构成的字符串,最后比较map1和map的values是否相同。
代码(java):
class Solution {
public boolean wordPattern(String pattern, String str) {
HashMap<Character,String> map=new HashMap<Character,String>();
for(int i=0;i<pattern.length();i++){
if(map.keySet().contains(pattern.charAt(i))){
String tmp=map.get(pattern.charAt(i));
tmp+=i;
map.put(pattern.charAt(i),tmp);
}
else{
String tmp="";
tmp+=i;
map.put(pattern.charAt(i),tmp);
}
}
String []strSplit=str.split(" ");
HashMap<String,String> map1=new HashMap<String,String>();
for(int i=0;i<strSplit.length;i++){
if(map1.keySet().contains(strSplit[i])){
String tmp=map1.get(strSplit[i]);
tmp+=i;
map1.put(strSplit[i],tmp);
}
else{
String tmp="";
tmp+=i;
map1.put(strSplit[i],tmp);
}
}
return map.values().size()==map1.values().size() && map.values().containsAll(map1.values());
}
}
本文深入探讨了模式匹配算法,通过具体实例展示了如何判断两个字符串是否遵循相同的模式。文章提供了详细的解题思路,包括使用HashMap进行字符和单词位置的映射,并比较两者的模式一致性。
1861

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



