File tree Expand file tree Collapse file tree 1 file changed +5
-0
lines changed Expand file tree Collapse file tree 1 file changed +5
-0
lines changed Original file line number Diff line number Diff line change 4
4
class Solution {
5
5
public:
6
6
bool wordPattern (string pattern, string str) {
7
+ // Count the words.
7
8
int cnt = str.empty () ? 0 : 1 ;
8
9
for (const auto & c : str) {
9
10
if (c == ' ' ) {
@@ -18,15 +19,19 @@ class Solution {
18
19
unordered_map<char , string> p2w;
19
20
int i = 0 , j = 0 ;
20
21
for (const auto & p : pattern) {
22
+ // Get a word at a time without saving all the words.
21
23
j = str.find (" " , i);
22
24
if (j == string::npos) {
23
25
j = str.length ();
24
26
}
25
27
const string w = str.substr (i, j - i);
28
+
26
29
if (!w2p.count (w) && !p2w.count (p)) {
30
+ // Build mapping. Space: O(c)
27
31
w2p[w] = p;
28
32
p2w[p] = w;
29
33
} else if (!w2p.count (w) || w2p[w] != p) {
34
+ // Contradict mapping.
30
35
return false ;
31
36
}
32
37
i = j + 1 ;
You can’t perform that action at this time.
0 commit comments