###### 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;
}

#### Word Pattern

2015-10-09 23:18:56

#### [Leetcode]290. Word Pattern

2016-07-14 15:55:37

#### LeetCode题解：Word Pattern

2016-02-28 14:56:50

#### LeetCode 290 Word Pattern

2017-05-03 23:53:35

#### LEETCODE 290

2016-03-26 22:53:45

#### LeetCode290——Word Pattern

2015-11-28 14:50:58

#### 《leetCode》：Word Pattern

2016-04-08 20:15:32

#### Word Pattern问题及解法

2017-04-04 11:27:26

#### <LeetCode><Easy>290 Word Pattern

2015-10-14 13:20:56

#### LeetCode 290:Word Pattern

2015-12-20 18:04:46

## 不良信息举报

290. Word Pattern(技巧：记录当前位置来判断两个字符串是否符合)