您的位置:首页 > 其它

LeetCode 290:Word Pattern

2015-12-20 18:04 393 查看
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.

给定一个模式(pattern)和字符串(str),判断字符串是否遵循这个模式。

这意味着str与pattern是双向映射的,即一个str只对应一个pattern,一个pattern也只对应一个str。

例如:

pattern = 
"abba"
, str = 
"dog
cat cat dog"
 返回真。
pattern = 
"abba"
, str = 
"dog
cat cat fish"
 返回假。(第一个a < - > dog,然而最后一个a < - > fish)
pattern = 
"aaaa"
, str = 
"dog
cat cat dog"
 返回假。(第一个a < - >dog,然而第二个a < - > cat)
pattern = 
"abba"
, str = 
"dog
dog dog dog"
 返回假。(第一个a < - > dog,然而第一个b也b < - > dog)

由于我只会map,因此在建立双向映射的时候采取的办法是在每一个pattern后面加一个" "(即空格)来区分(以防止出现str为单个字母导致重复映射的情况)。大致思路是将str按空格分割放入vector<string>中,然后按顺序判断pattern与vector的每一对元素,若pattern或str出现过,那么判断对应映射是否正确;否则建立一对新的映射关系。

字符串分割算是自己勉勉强强写出来了,然而对于字符串的使用还是不够熟练。可以看到在判断循环中我先将pattern[i]来push_back给test,然后又append了一个空格进去。。。本来想直接用重载运算符+来直接写进去,但是好像并不能直接写的样子。

class Solution {
public:
bool wordPattern(string pattern, string str) {
map<string,string> mapl;
vector<string> vec;
str.append(" ");
for(int start=0,count=0;start<str.length();count++)
{
if(str[start+count]==' ')
{
vec.push_back(str.substr(start,count));
start+=count+1;
count=0;
}
}
if(pattern.length()!=vec.size()) return false;
for(int i=0;i<pattern.length();i++)
{
string test;
test.push_back(pattern[i]);
test.append(" ");
if(mapl.count(test)||mapl.count(vec[i]))
{

if(mapl[test]!=vec[i]||mapl[vec[i]]!=test) return false;
}
else
{
mapl[test]=vec[i];
mapl[vec[i]]=test;
}
}
return true;
}
};


这里推荐一篇博客,对C++的字符串函数有非常非常详尽的解释,强烈推荐。另外,如果对于C++ STL有像这样介绍详细的博客(关键是要有清晰的成员函数列表及其对应函数参数,不需要使用实例),也请推荐给我,谢谢。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: