思路:hash索引肯定要用的,但这道题我既要让单词对应字符,也要判断这个单词所对应的字符是否已被别的单词对应,所以我用了两个map,方便判断;一个是map<string,char>
,一个是map<char,string>
;
bool wordPattern(string pattern, string s)
{
int len = s.size();
map<char, string> m1;
map<string, char> m2;
int index = 0;
for (int left = 0, right = 0; right <= len; right++)
{
if (right == len || s[right] == ' ')
{
//得到单词temp
string temp = s.substr(left, right - left);
//如果m2中没找到temp
if (m2.find(temp) == m2.end())
{
m2[temp] = pattern[index];
//m1中有单词与当前字符对应,并且单词与temp不同,说明不匹配;
if (m1.find(pattern[index]) != m1.end() && m1.find(pattern[index])->second != temp)
return false;
else //m1中没有这个单词,则插入;
m1[pattern[index]] = temp;
}
else //如果m2中找到了单词temp,那最好了,直接判断;
{
if (m2.find(temp)->second != pattern[index])
return false;
}
index++;
left = right + 1;
}
}
//此时如果pattern与单词全部匹配上了,index应该指向pattern的末尾;
if (index != pattern.size())
return false;
return true;
}