Given a pattern
and a string str
, find if str
follows the same pattern.
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:
pattern
contains only lowercase alphabetical letters, andstr
contains words separated by a single space. Each word instr
contains only lowercase alphabetical letters.- Both
pattern
andstr
do not have leading or trailing spaces. - Each letter in
pattern
must map to a word with length that is at least 1.
Credits:
Special thanks to @minglotus6 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;
}
};
其他leetcode题目AC代码: https://github.com/PoughER