Update 290. Word Pattern.md

This commit is contained in:
ShusenTang 2020-07-25 11:12:30 +08:00 committed by GitHub
parent 827105a6fe
commit bcb6cde23e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -3,6 +3,11 @@
类似[205. Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/description/), 所以解题思路基本一样。
将pattern和str中个每个元素都用一个数代替,这个数代表了该元素是第几个出现的(如 "abba" -> 1221, "dog cat cat dog" -> 1221), 则结果应该是一样的。
为了记录是否出现过pattern用一个长度为26的数组实现str用map来实现此外还用一个count计数。
更新:
可以用`istringstream`很方便地将`str`按照空格分开。
# C++
```C++
class Solution {
@ -32,3 +37,34 @@ public:
}
};
```
更新:
``` C++
class Solution {
public:
bool wordPattern(string pattern, string str) {
unordered_map<char, int>c_mp;
vector<int>c2int;
unordered_map<string, int>str_mp;
int count = 0;
for(char c: pattern){
if(c_mp.find(c) == c_mp.end()) c_mp[c] = count++;
c2int.push_back(c_mp[c]);
}
count = 0;
int i = 0;
string cur;
istringstream iss(str);
while(iss.good()){ // or !iss.eof()
iss >> cur;
if(str_mp.find(cur) == str_mp.end()) str_mp[cur] = count++;
if(i >= c2int.size() || c2int[i] != str_mp[cur]) return false;
i++;
}
return i == c2int.size();
}
};
```