# 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:

1. pattern = "abba", str = "dog cat cat dog" should return true.
2. pattern = "abba", str = "dog cat cat fish" should return false.
3. pattern = "aaaa", str = "dog cat cat dog" should return false.
4. 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.

1.我的答案

class Solution {
public:
bool wordPattern(string pattern, string str) {
map<char,int>map_p;
map<string,int>map_s;
vector<string> vec;
string s = "";
int len_pat = pattern.size();
for(int i = 0; i < str.size(); i++){
if(str[i] == ' '){
vec.push_back(s);
s = "";
continue;
}
s += str[i];
}
vec.push_back(s);
int len_str = vec.size();
if(len_pat != len_str)
return false;
for(int k = 0; k < len_str; k++){
if(map_p.find(pattern[k]) == map_p.end())
map_p[pattern[k]] = k;
if(map_s.find(vec[k]) == map_s.end())
map_s[vec[k]] = k;
if(map_p[pattern[k]] == map_s[vec[k]]){
map_p[pattern[k]] = k;
map_s[vec[k]] = k;
}else
return false;
}
return true;
}
};

2.大神的代码  真是膜拜啊啊！

bool wordPattern(string pattern, string str) {
map<char, int> p2i;
map<string, int> w2i;
istringstream in(str);
int i = 0, n = pattern.size();
for (string word; in >> word; ++i) {
if (i == n || p2i[pattern[i]] != w2i[word])
return false;
p2i[pattern[i]] = w2i[word] = i + 1;
}
return i == n;
}

• 本文已收录于以下专栏：

举报原因： 您举报文章：290. Word Pattern(技巧：记录当前位置来判断两个字符串是否符合) 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)