Skip to content

Commit a62a43f

Browse files
committed
Update word-pattern.cpp
1 parent 46dd7d4 commit a62a43f

File tree

1 file changed

+5
-0
lines changed

1 file changed

+5
-0
lines changed

C++/word-pattern.cpp

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
class Solution {
55
public:
66
bool wordPattern(string pattern, string str) {
7+
// Count the words.
78
int cnt = str.empty() ? 0 : 1;
89
for (const auto& c : str) {
910
if (c == ' ') {
@@ -18,15 +19,19 @@ class Solution {
1819
unordered_map<char, string> p2w;
1920
int i = 0, j = 0;
2021
for (const auto& p : pattern) {
22+
// Get a word at a time without saving all the words.
2123
j = str.find(" ", i);
2224
if (j == string::npos) {
2325
j = str.length();
2426
}
2527
const string w = str.substr(i, j - i);
28+
2629
if (!w2p.count(w) && !p2w.count(p)) {
30+
// Build mapping. Space: O(c)
2731
w2p[w] = p;
2832
p2w[p] = w;
2933
} else if (!w2p.count(w) || w2p[w] != p) {
34+
// Contradict mapping.
3035
return false;
3136
}
3237
i = j + 1;

0 commit comments

Comments
 (0)