首页 > 其他 > 详细

[LeetCode]Word Pattern

时间:2015-10-11 13:59:45      阅读:401      评论:0      收藏:0      [点我收藏+]

题目描述:(链接

Given a pattern and a string str, find if str follows the same pattern.

Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.

Examples:

  1. pattern = "abba", str = "dog cat cat dog" should return true.
  2. pattern = "abba", str = "dog cat cat fish" should return false.
  3. pattern = "aaaa", str = "dog cat cat dog" should return false.
  4. pattern = "abba", str = "dog dog dog dog" should return false.

 

Notes:
You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.

解题思路:

找到字符和字符串之间的映射关系就行了,用两个哈希表分别存放<字符,字符串>和<字符串, 字符>的映射关系,前提需要分解字符串(split函数)。

 1 class Solution {
 2 public:
 3     bool wordPattern(string pattern, string str) {
 4         unordered_map<char, string> cache1;
 5         unordered_map<string, char> cache2;
 6         
 7         vector<string> splitStrs = split(str,  );
 8         
 9         if (splitStrs.size() != pattern.size()) {
10             return false;
11         }
12         
13         for (size_t i = 0; i < pattern.size(); ++i) {
14             if (cache1.find(pattern[i]) == cache1.end() && cache2.find(splitStrs[i]) == cache2.end()) {
15                 cache1[pattern[i]] = splitStrs[i];
16                 cache2[splitStrs[i]] = pattern[i];
17             } else if (cache1.find(pattern[i]) != cache1.end() && cache2.find(splitStrs[i]) != cache2.end()){
18                 if (cache1[pattern[i]] != splitStrs[i] && cache2[splitStrs[i]] != pattern[i]) {
19                     return false;
20                 }
21             } else {
22                 return false;
23             }
24         }
25         
26         return true;
27     }
28 private:
29     vector<string> split(const string& src, char sep) {
30         vector<string> result;
31         size_t lastIndex = 0;
32         size_t index = 0;
33         while ((index = src.find(sep, lastIndex)) != string::npos) {
34             result.push_back(src.substr(lastIndex, index - lastIndex));
35             lastIndex = index + 1;
36         }
37         
38         string lastStr = src.substr(lastIndex);
39         if (!lastStr.empty()) {
40             result.push_back(lastStr);
41         }
42         
43         return result;
44     }
45 };

 

[LeetCode]Word Pattern

原文:http://www.cnblogs.com/skycore/p/4869150.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!