【题目描述】
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
.
Examples:
- pattern =
"abba"
, str ="dog cat cat dog"
should return true. - pattern =
"abba"
, str ="dog cat cat fish"
should return false. - pattern =
"aaaa"
, str ="dog cat cat dog"
should return false. - pattern =
"abba"
, str ="dog dog dog dog"
should return false.
Notes:
You may assume pattern
contains only lowercase letters, and str
contains lowercase letters separated by a single space.
【思路】
参考了别人的思路,发现自己在哈希表方面的知识还是不足。
晚上又自己实现了一遍c++版本的,思路是用了一个map和一个set,map记录pattern里每个字符和str中的字符串的对应关系,如果在map中找到pattern该字符,则判断该字符对应的字符串是否为str中相同位置对应的字符串,不是则返回false,如果在map中没有找到,则在set中寻找是否存在该字符串,如果存在则意味该字符串对应着两个不同的字符,返回false,反之则分别往map和set中添加对应的数据。
【代码】
java版本:
public class Solution {
public boolean wordPattern(String pattern, String str) {
String strs[]=str.split(" ");
int slen=strs.length;
int plen=pattern.length();
if(slen!=plen) return false;
Map<Character, String> strmap = new HashMap<>();
Set<String>strset=new HashSet();
for(int i=0;i<slen;i++){
char c=pattern.charAt(i);
if(strmap.containsKey(c)){
if(strmap.get(c).equals(strs[i])==false) return false;
}
else{
if(strset.contains(strs[i])) return false;
else{
strmap.put(c,strs[i]);
strset.add(strs[i]);
}
}
}
return true;
}
}
c++版本:
class Solution {
public:
bool wordPattern(string pattern, string str) {
vector<string> vec;
string word="";
int slen=str.length();
int plen=pattern.length();
int cnt=0;
for(int i=0;i<slen;i++){
if(str[i]==' '){
vec.push_back(word);
word="";
cnt++;
continue;
}
word=word+str[i];
}
vec.push_back(word);
cnt++;
if(cnt!=plen) return false;
map<char,string> strmap;
set<string>strset;
for(int i=0;i<cnt;i++){
char c=pattern[i];
if(strmap.find(c)!=strmap.end()){
string s=strmap[c];
if(s!=vec[i]) return false;
}
else{
if(strset.find(vec[i])!=strset.end()) return false;
else{
strmap[c]=vec[i];
strset.insert(vec[i]);
}
}
}
return true;
}
};