原题:
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.
题意:
给你一个模式串和一个字符串,其中模式串中一个字母代表一种字符串,现在问你字符串和模式串能不能匹配上。
class Solution
{
map<char,string> mc;
map<string,char> ms;
vector<string> vs;
public:
bool wordPattern(string pattern, string str)
{
mc.clear();
ms.clear();
vs.clear();
str+=" ";
int pos=0;
for(int j=0;j<str.size();j++)
{
if(str[j]==' ')
{
string tmp=str.substr(pos,j-pos);
pos=j+1;
vs.push_back(tmp);
}
}
if(vs.size()!=pattern.size())
return false;
for(int i=0;i<pattern.size();i++)
{
char c=pattern[i];
if(mc[c]==""&&ms[vs[i]]==0)
{
mc[c]=vs[i];
ms[vs[i]]=c;
}
else
{
if(mc[c]!=vs[i]||ms[vs[i]]!=c)
return false;
}
}
return true;
}
};
解答:
首先把给的字符串按空格拆开存起来,然后建立两个映射表,一个是模式串中的字符对应于单词,另一个是单词对应模式串里的字符。首先,如果模式串里的字母数和单词的数量不对应那肯定是false,否则判断双向映射是否匹配即可~