pattern和substr的对应应该是双向的,因此设置双向的比较。
Solution
bool wordPattern(string pattern, string str)
{
map<char, string> m;
map<string, char> p;
int begin = 0, end = 0;
int index = 0;
string token;
while(index < pattern.length() && end <= str.length())
{
if(end == str.length() || str[end] == ' ')
{
token.assign(str, begin, end - begin);
// token -> pattern
if(m.find(pattern[index]) == m.end())
m[pattern[index]] = token;
else if(m[pattern[index]] != token)
return false;
// pattern -> token
if(p.find(token) == p.end())
p[token] = pattern[index];
else if(p[token] != pattern[index])
return false;
begin = end + 1;
index++;
}
end++;
}
if(index != pattern.length() || end != str.length() + 1)
return false;
return true;
}