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

LeetCode 290. Word Pattern

时间:2016-03-05 22:03:30      阅读:306      评论:0      收藏:0      [点我收藏+]

标签:

不符合的情况有三种:1、pattern和str长度不符   2、pattern中不同字母指向str中同一词(a、b->同一词)   3、同一字母指向不同词(a->不同词)

 

 1 class Solution {
 2 public:
 3     vector<string> split(string str){
 4         vector<string> res;
 5         string tmp = "";
 6         for(int i = 0; i < str.length(); ++i){
 7             if(str[i] !=  ) {
 8                 if(i == str.length() - 1) res.push_back(tmp + str[i]);
 9                 tmp += str[i];
10             }
11             else{
12                 res.push_back(tmp);
13                 tmp = "";
14             }
15         }
16         return res;
17     }
18     bool wordPattern(string pattern, string str) {
19         vector<string> res = split(str);
20         
21         if(pattern.length() != res.size()) return false;
22         map<char, string> corre;
23         map<char, string>::iterator it;
24         set<string> word;
25         set<string>::iterator itr;
26         for(int i = 0; i < pattern.length(); ++i){
27             it = corre.find(pattern[i]);
28             if(it == corre.end()){
29                 itr = word.find(res[i]);
30                 if(itr != word.end()) return false;
31                 corre.insert(pair<char, string>(pattern[i], res[i]));
32                 word.insert(res[i]);
33             }
34             else{
35                 if(it->second != res[i]) return false;
36             }
37         }
38         return true;
39     }
40 };

map存字母和单词的对应关系,set存出现过的单词。

if(it == corre.end()) 即该字母未出现过,如果对应的单词已出现,则代表多字母对应同一词,return false.
else 该字母出现过,如果之前出现过的同一字母对应的却是不同的单词,return false.


LeetCode 290. Word Pattern

标签:

原文地址:http://www.cnblogs.com/co0oder/p/5245878.html

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