2018-09-14 12:37:37 +00:00
|
|
|
|
# [290. Word Pattern](https://leetcode.com/problems/word-pattern/description/)
|
|
|
|
|
# 思路
|
|
|
|
|
类似[205. Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/description/), 所以解题思路基本一样。
|
|
|
|
|
将pattern和str中个每个元素都用一个数代替,这个数代表了该元素是第几个出现的(如 "abba" -> 1221, "dog cat cat dog" -> 1221), 则结果应该是一样的。
|
|
|
|
|
为了记录是否出现过,pattern用一个长度为26的数组实现,str用map来实现,此外还用一个count计数。
|
|
|
|
|
# C++
|
2019-09-13 15:08:41 +00:00
|
|
|
|
```C++
|
2018-09-14 12:37:37 +00:00
|
|
|
|
class Solution {
|
|
|
|
|
public:
|
|
|
|
|
bool wordPattern(string pattern, string str) {
|
|
|
|
|
map<string, int>mp;
|
|
|
|
|
vector<int>vc(26, 0);
|
|
|
|
|
string sub_str;
|
|
|
|
|
int count = 1, pos = 0, pre; // pos记录空格的下一个位置,pre为上一个空格位置的下一个位置
|
|
|
|
|
for(int i = 0; i < pattern.size(); i++){
|
|
|
|
|
if(pos >= str.size()) return false; // str中元素少于pattern中的元素
|
|
|
|
|
pre = pos;
|
|
|
|
|
while(str[pos] != ' ' && pos < str.size()) pos++; // 此时pos为空格的位置或str结束位置
|
|
|
|
|
// s.substr(pos1,n)返回字符串s从pos1开始n个字符组成的串
|
|
|
|
|
sub_str = str.substr(pre, pos - pre);
|
|
|
|
|
pos++; // pos记录空格的下一个位置
|
|
|
|
|
|
|
|
|
|
// 以下代码基本同205题
|
|
|
|
|
if(vc[pattern[i] - 'a'] != mp[sub_str]) return false;
|
|
|
|
|
if(vc[pattern[i] - 'a'] == 0){
|
|
|
|
|
vc[pattern[i] - 'a'] = count;
|
|
|
|
|
mp[sub_str] = count++;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
if(pos != str.size() + 1) return false; // str中元素多余pattern中的元素
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
```
|