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

LeetCode OJ:Word Pattern(单词模式)

时间:2016-01-03 22:29:01      阅读:243      评论: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.

跟前面一篇博文类似,都是用map来检查单词是否已经处理过,代码如下:

 1 class Solution {
 2 public:
 3     bool wordPattern(string pattern, string str) {
 4           stringstream ss(str);
 5           vector<string> tmpVec;
 6           string tmp;
 7           while(ss >> tmp)
 8               tmpVec.push_back(tmp);
 9           if(tmpVec.size() != pattern.size())
10               return false;
11           map<char, string> m1;
12           map<string, char> m2;
13           for(int i = 0; i < pattern.size(); ++i){
14               tmp = tmpVec[i];
15               if(m1.find(pattern[i]) == m1.end() && m2.find(tmp) == m2.end()){
16                   m1[pattern[i]] = tmp;
17                   m2[tmp] = pattern[i];
18               }else if(m1.find(pattern[i]) != m1.end() && m2.find(tmp) != m2.end()){
19                   if(m1[pattern[i]] != tmp || m2[tmp] != pattern[i])
20                       return false;
21               }else{
22                       return false;
23               }
24           }
25           return true;      
26     }
27 };

 

LeetCode OJ:Word Pattern(单词模式)

标签:

原文地址:http://www.cnblogs.com/-wang-cheng/p/4989166.html

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