1
1
// Time: O(n)
2
- // Space: O(c), c is unique count of pattern and words
2
+ // Space: O(c), c is count of pattern
3
3
4
4
class Solution {
5
5
public:
@@ -16,21 +16,20 @@ class Solution {
16
16
17
17
unordered_map<string, char > word2pattern;
18
18
unordered_map<char , string> pattern2word;
19
- for (int i = 0 , idx = 0 , space_idx = 0 ;
20
- i < pattern.size ();
21
- ++i, idx = space_idx + 1 ) {
22
-
23
- space_idx = str.find (" " , idx) != string::npos ?
24
- str.find (" " , idx) :
25
- str.length ();
26
- string word = str.substr (idx, space_idx - idx);
27
- if (word2pattern[word] == 0 &&
28
- pattern2word[pattern[i]] == " " ) {
29
- word2pattern[word] = pattern[i];
30
- pattern2word[pattern[i]] = word;
31
- } else if (word2pattern[word] != pattern[i]) {
19
+ int i = 0 , j = 0 ;
20
+ for (const auto & p : pattern) {
21
+ j = str.find (" " , i);
22
+ if (j == string::npos) {
23
+ j = str.length ();
24
+ }
25
+ string word = str.substr (i, j - i);
26
+ if (!word2pattern.count (word) && !pattern2word.count (p)) {
27
+ word2pattern[word] = p;
28
+ pattern2word[p] = word;
29
+ } else if (word2pattern[word] != p) {
32
30
return false ;
33
31
}
32
+ i = j + 1 ;
34
33
}
35
34
return true ;
36
35
}
0 commit comments