您的位置:首页 > 其它

290. Word Pattern

2016-05-14 10:35 169 查看
290. Word Pattern

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.


感觉自己的方法比较笨,不过相对自己以前的编码习惯,在按照空格分割string时,引用istringstream的确是一种比较快捷的方法。

解决这个问题的主要思想:

pattern:abba,我们编码为0110;对于pattern中的每个字符,我们将其映射到其第一次出现的位置,这个可以直接利用string的find_first_of得到。

str = “dog cat cat fish”,我们编码为0113;对于vector来说,如何实现将每个单词映射到其第一次出现的位置,我引用了map。

class Solution {
public:
bool wordPattern(string pattern, string str) {
int* patternCode=new int[pattern.size()];//对pattern进行编码
for(unsigned int i=0;i<pattern.size();i++)
patternCode[i]=pattern.find_first_of(pattern[i]);
vector<string> vec;
map<string,int> strMap;
istringstream ss(str);
string word;
while(ss>>word)
vec.push_back(word);//分割str为单词,存储在vector中
int* strCode=new int[vec.size()];
for(unsigned int i=0;i<vec.size();i++)//为str进行编码
{
if(!strMap.count(vec[i]))
{
strMap[vec[i]]=i;
strCode[i]=i;
}
else
strCode[i]=strMap[vec[i]];

}
if(pattern.size()!=vec.size())//两者编码长度不同,返回错误
return false;
for(unsigned int i=0;i<vec.size();i++)
if(patternCode[i]!=strCode[i])
return false;
return true;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: