Given a pattern
and a string str
, find if str
follows the same pattern.
Examples:
Notes:
pattern
contains only lowercase alphabetical letters, and str
contains words separated by a single space. Each word in str
contains only lowercase alphabetical letters.pattern
and str
do not have leading or trailing spaces.pattern
must map to a word with length that is at least 1.
Credits:
Special thanks to for adding this problem and creating all test cases.
字符与字符串的匹配
AC代码:
class Solution {
public:
bool wordPattern(string pattern, string str) {
vector<string> temp=stringTovec(str);
int len=pattern.size();
int sum=temp.size();
map<char,string> m;
map<string,char> m2;
int j=0;
for(int i=0;i<len;++i)
{
if(m.find(pattern[i])!=m.end())
{
if(j<sum&&m[pattern[i]]==temp[j])
{
++j;
continue;
}
else
return false;
}
else if(j<sum)
{
m[pattern[i]]=temp[j];
++j;
}
else
return false;
}
j=0;
for(int i=0;i<sum;++i)
{
if(m2.find(temp[i])!=m2.end())
{
if(m2[temp[i]]==pattern[j])
{
++j;
continue;
}
else
return false;
}
else if(j<len)
{
m2[temp[i]]=pattern[j];
++j;
}
else
return false;
}
return true;
}
private:
vector<string> stringTovec(string s)
{
vector<string> res;
int len=s.size();
string temp="";
for(int i=0;i<len;++i)
{
if(s[i]==' ')
{
res.push_back(temp);
temp="";
}
else
temp+=s[i];
}
res.push_back(temp);
return res;
}
};
因篇幅问题不能全部显示,请点此查看更多更全内容