描述
给定一个模式
和一个字符串str
,查找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
。
感觉自己的方法虽然思路简单,但是空间复杂度太高了。
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> result;
string tmp;
for(int i=0;i<str.length();i++){
if(str[i]==' '&&tmp.length()>0){
result.push_back(tmp);
tmp="";
}else tmp+=str[i];
}
if(tmp.length()>0) result.push_back(tmp);
unordered_map<char,string> m_map1;
unordered_map<string,char> m_map2;
for(int i=0;i<pattern.length();i++){
if(m_map1.count(pattern[i])==0) {
m_map1[pattern[i]]=result[i];
m_map2[result[i]]=pattern[i];
}
else if(m_map1[pattern[i]]!=result[i]||m_map2[result[i]]!=pattern[i]) return false;
}
return true;
}
};