Skip to content

Commit 513e8d6

Browse files
committed
Update word-pattern.cpp
1 parent 655f5bc commit 513e8d6

File tree

1 file changed

+13
-14
lines changed

1 file changed

+13
-14
lines changed

C++/word-pattern.cpp

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
// Time: O(n)
2-
// Space: O(c), c is unique count of pattern and words
2+
// Space: O(c), c is count of pattern
33

44
class Solution {
55
public:
@@ -16,21 +16,20 @@ class Solution {
1616

1717
unordered_map<string, char> word2pattern;
1818
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) {
3230
return false;
3331
}
32+
i = j + 1;
3433
}
3534
return true;
3635
}

0 commit comments

Comments
 (0)