码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Word Pattern

时间:2015-10-06 23:28:41      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:

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 :-)

[LeetCode] Word Pattern

标签:

原文地址:http://www.cnblogs.com/jcliBlogger/p/4857854.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!