给定一种 pattern(模式)
和一个字符串 str
,判断 str
是否遵循相同的模式。
这里的遵循指完全匹配,例如, pattern
里的每个字母和字符串 str
中的每个非空单词之间存在着双向连接的对应模式。
示例1:
输入: pattern = "abba", str = "dog cat cat dog" 输出: true
示例 2:
输入:pattern = "abba", str = "dog cat cat fish" 输出: false
示例 3:
输入: pattern = "aaaa", str = "dog cat cat dog" 输出: false
示例 4:
输入: pattern = "abba" , str = "dog dog dog dog" 输出: false
class Solution {
public:
bool wordPattern(string pattern, string str) {
if(pattern.length()==0 && str.length()!=0)
return 0;
vector<string> vec;
for(int i=0;str[i] != '\0';i++)
{
int index = str.find(' ');
if(index!=-1)
{
string s(str,0,index);
vec.push_back(s);
str.erase(str.begin(),str.begin()+index+1);
i=-1;
}
}
vec.push_back(str);
for(int i=0;i<pattern.size();i++)
{
int index = pattern.find(pattern[i],i+1);
if(index==-1)//不存在相等
{
vector<string>::iterator it = find(vec.begin()+1+i,vec.end(),vec[i]);
if(it != vec.end())
return 0;
}
else//存在相等
{
if(vec[i] != vec[index])
return 0;
}
}
if(pattern.length()!=1 && vec.size()==1)
return 0;
return 1;
}
};