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.
四种情况的测试:
abba/dog cat cat dog/true
abba/dog cat cat fish/false
abba/dog dog dog dog/false
abba/dog cat cat dog dog/false
Code
class Solution {
public:
bool wordPattern(string pattern, string str) {
std::map<char, string> smap;
std::set<string> sset;
string currentStr;
char currentChar;
int len = pattern.length();
stringstream strs(str);
bool res=true;
for(int i=0; i<len; i++)
{
if(strs.eof())
{
res=false;
break;
}
strs>>currentStr;
currentChar = pattern[i];
if(smap.find(currentChar) != smap.end())
{
if(!(smap[currentChar] == currentStr))
{
res=false;
break;
}
}
else
{
if(sset.find(currentStr) == sset.end())
{
smap[currentChar] = currentStr;
sset.insert(currentStr);
}
else
{
res = false;
break;
}
}
}
if(!strs.eof())
{
res=false;
}
return res;
}
};