给定一个模式
和一个字符串str
,查找str
是否遵循相同的模式。
这里遵循的意思是一个完整的匹配,在一个字母的模式
和一个非空的单词str
之间有一个双向连接的模式对应。
样例
给定模式= "abba"
, str = "dog cat cat dog"
,返回true
。给定模式= "abba"
, str = "dog cat cat fish"
,返回false
。
给定模式= "aaaa"
, str = "dog cat cat dog"
,返回false
。给定模式= "abba"
, str = "dog dog dog dog"
,返回false
。
解题思路:
建立两个哈希表,双向对应。为建立映射方便,首先将str中的每个单词放进vector中。然后遍历整个patten与words,在依次建立映射的过程中也检验当前映射是否存在与正确,遍历完毕则返回true。
class Solution {
public:
/**
* @param pattern: a string, denote pattern string
* @param str: a string, denote matching string
* @return: an boolean, denote whether the pattern string and the matching string match or not
*/
bool wordPattern(string &pattern, string &str)
{
// write your code here
vector<string> words = split(str);
if(pattern.size() != words.size())
return false;
unordered_map<char,string> map1;
unordered_map<string,char> map2;
for(int i=0;i<pattern.size();i++)
{
if(map1.count(pattern[i])==0)//如果在map1中没找到映射单词
{
if(map2.count(words[i])>0)//此时map2中若有该映射,则错误
return false;
//添加该映射
map1[pattern[i]] = words[i];
map2[words[i]] = pattern[i];
}
else//如果在map1中找到了映射单词
{
if(map2.count(words[i])==0)//此时map2中若没有该映射,则错误
return false;
if(map1[pattern[i]] != words[i] || map2[words[i]] != pattern[i])//如果两者映射不对应,则错误
return false;
}
}
return true;
}
//将str中的单词提取出来存储与vector中,方便建立映射
vector<string> split(const string &str)
{
vector<string> res;
string tmp;
for(int i=0;i<=str.size();i++)
{
if(str[i]==' ' || str[i]=='\0')
{
res.push_back(tmp);
tmp.clear();
}
else
{
tmp += str[i];
}
}
return res;
}
};