您的位置:首页 > 其它

290. Word Pattern

2015-11-30 15:51 176 查看
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.
Credits:

Special thanks to @minglotus6 for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

Hide Tags
 Hash Table

Show Similar Problems

每个字母对应一个单词,且不同字母要对应不同的单词。

所以使用两个哈希表(一开始没注意,不同字母要对应不同的单词),一个用来记录字母和单词的对应,一个用来记录单词是否已经出现过。

205. Isomorphic Strings几乎是一样的题。

另外,注意文中分词的方法,结合 


c++字符串分词

class Solution {
public:
void splitWords(std::string& s, std::string& delim,std::vector<string >& ret)
{
size_t last = 0;
size_t index=s.find_first_of(delim,last);
while (index!=std::string::npos)
{
ret.push_back(s.substr(last,index-last));
last=index+1;
index=s.find_first_of(delim,last);
}
if (index-last>0)
{
ret.push_back(s.substr(last,index-last));
}
}
bool wordPattern(string pattern, string str) {

vector<string> strVec;
string delim = " ";
splitWords(str,delim,strVec);
if(strVec.size() != pattern.length())
return false;

unordered_map<string,char> str2pattern;
unordered_map<char,string> pattern2str;
for(int i = 0;i<pattern.length();++i)
{
if(str2pattern.find(strVec[i]) != str2pattern.end() && str2pattern[strVec[i]] !=pattern[i]
|| pattern2str.find(pattern[i]) != pattern2str.end() && pattern2str[pattern[i]] !=strVec[i])
return false;
str2pattern[strVec[i]] =pattern[i];
pattern2str[pattern[i]] =strVec[i];
}

return true;

}
};


class Solution {
public:
bool wordPattern(string pattern, string str) {

vector<string> wordsVec;
map<char, string> hash_table1;
map<string, bool> hash_table2;

stringstream ss(str);
string curStr;
while (getline(ss, curStr, ' '))
{
wordsVec.push_back(curStr);
}

if (pattern.length() != wordsVec.size())
{
return false;
}

for (int i = 0; i < pattern.length();++i)
{
if (hash_table1.find(pattern[i]) == hash_table1.end())
{
if (hash_table2[wordsVec[i]] == true)
{
return false;
}
else
{
hash_table1[pattern[i]] = wordsVec[i];
hash_table2[wordsVec[i]] = true;
}
}
else
{
if (hash_table1[pattern[i]] != wordsVec[i])
{
return false;
}
}
}

return true;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: