您的位置:首页 > 其它

leetcode Word Pattern

2015-12-16 11:13 344 查看
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.

这个题和判断连个字符串是否同构是类似的,会那一道这一道就不成问题了。

只是多了一个字符串分割,我自己写了一个关于字符串分割的函数。除此之外需要构建两个map,一个是map<string,char>一个是map<char,string>

然后就是没有什么难度了,有一个问题就是我在vs2010里mp[pattern[i]]!=v1[i]这句提示不能用“!=”(原来我是没有#include<string>太粗心啦)不过在leetcode的编译器里通过了。

我需要看一下关于字符串的比较。

class Solution {
public:
vector<string> splitString(string s){
vector<string> result;
string temp;
int length=s.length();
for(int i=0;i<length;i++){
if(s[i]!=' '&&i!=length-1) temp+=s[i];
else {
if(i==length-1) temp+=s[i];
result.push_back(temp);
temp="";
}
}
return result;
}

bool wordPattern(string pattern, string str) {
vector<string> v1;
v1=splitString(str);
if(pattern.length()!=v1.size()) return false;
map<char,string> mp;
for(int i=0;i<pattern.length();i++){
if(mp.find(pattern[i])==mp.end()) mp[pattern[i]]=v1[i];
else if(mp[pattern[i]]!=v1[i]) return false;
}
map<string,char> mp2;
for(int i=0;i<pattern.length();i++){
if(mp2.find(v1[i])==mp2.end()) mp2[v1[i]]=pattern[i];
else if(mp2[v1[i]]!=pattern[i]) return false;
}
return true;
}
};


这是别人这道题分割字符串的方法,学习了:

while (sin >> tmp) dic.push_back(tmp);
if (dic.size() != pattern.size()) return false;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: