Given a pattern and a string str, find if str follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.
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:
You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.
class Solution {
public:
bool wordPattern(string pattern, string str) {
vector<string> store;
str=str+" ";
int len=str.size();
int pos=0;
for(int i=0;i<len;i++ )
{
pos=str.find(' ',i);
if(pos<len)
{
store.push_back(str.substr(i,pos-i));
i=pos;
}
}
map<char,string>maps;
int count=0;
for(char c:pattern)
{
if(count>=store.size()) return false;
if(maps.find(c)==maps.end())
{
maps[c]=store[count];
count++;
}
else
{
if(maps[c]!=store[count])
{
return false;
}
count++;
}
}
if(pattern.size()!=store.size()) return false;
for(int i=0;i<maps.size();i++)
{
for(int j=i+1;j<maps.size();j++)
{
if((maps[pattern[i]]==maps[pattern[j]])&&(pattern[i]!=pattern[j]))
return false;
}
}
return true;
}
};
思路:
就是把字符串安装空格分开(由于stl中没有spilt函数,需要自己实现,这里的idea是把标志位符添加到最后,然后用find和substr来实现)。然后用哈希表对应pattern每一个字符和存储所有string的store中的string,若已有相同key值,则看是否相同,不同则报false。若无相同key值,则增加这个key和string。最后比较每个key值对应的string有无相同,若有相同string对应不同key,则false。
第二遍自己做出来的,比原来的方法更简单,值得关注的是,这道题的test case比较刁钻,很容易错。
class Solution {
public:
bool wordPattern(string pattern, string str) {
vector<string> lists;
vector<string> maps(26,"");
for(int i=0;i<str.size();){
int j=i;
for(;j<str.size();j++){
if(str[j]==' '){
lists.push_back(str.substr(i,j-i));
break;
}
}
if(j==str.size()){
lists.push_back(str.substr(i,j-i));}
i=j+1;
}
if(pattern.size()!=lists.size()) return false;//很有用 防止"aaa"
// "aa aa aa aa"这种案例出现
int s=0;
for(char c:pattern){
if(maps[c-'a']==""){
maps[c-'a']=lists[s];
s++;
}
else{
if(maps[c-'a']!=lists[s]){
return false;
}
s++;
}
}
for(int i=0;i<maps.size();i++){
if(maps[i]=="") continue;
for(int j=i+1;j<maps.size();j++){
if(maps[i]==maps[j]&&maps[j]!="")
{
return false;
}
}
}
return true;
}
};
注意的test case 还有
“aaa”
“aa aa aa aa”
和
“query”
“query”