[LeetCode] Word Pattern

This problem can be solved in very neat codes (yeah, you will see Stefan posting many nice solutions).

The solution in the above link is so nice that I can almost do nothing to improve it instead of using unordered_map -_-

 1 class Solution {
 2 public:
 3     bool wordPattern(string pattern, string str) {
 4         unordered_map<char, int> p2i;
 5         unordered_map<string, int> w2i;
 6         istringstream in(str);
 7         int i = 0, n = pattern.length();
 8         for (string word; in >> word; i++) {
 9             if (i >= n || p2i[pattern[i]] != w2i[word])
10                 return false;
11             p2i[pattern[i]] = w2i[word] = i + 1;
12         }
13         return i == n;
14     }
15 };

If you wonder why it uses i + 1 instead of simply using i as the values, I mention it at the first comment in the above link :-)

posted @ 2015-10-06 22:10  jianchao-li  阅读(421)  评论(0编辑  收藏  举报