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

290. Word Pattern(LeetCode)

时间:2017-07-05 15:18:20      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:word   sam   als   ted   nbsp   space   tor   ring   contain   

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.

 1 class Solution {
 2 public:
 3     bool wordPattern(string pattern, string str) {
 4        istringstream strcin(str);
 5         string s;
 6         vector<string> vs;
 7         while(strcin >> s) vs.push_back(s);
 8         if (pattern.size() != vs.size()) return false;
 9         map<string, char> s2c;
10         map<char, string> c2s;
11         for (int i = 0; i < vs.size(); ++i) {
12             if (s2c[vs[i]] == 0 && c2s[pattern[i]] == "") { 
13                 s2c[vs[i]] = pattern[i]; 
14                 c2s[pattern[i]] = vs[i]; 
15                 continue; 
16             }
17             if (s2c[vs[i]] != pattern[i]) return false;
18         }
19         return true;
20     }
21 };

 

290. Word Pattern(LeetCode)

标签:word   sam   als   ted   nbsp   space   tor   ring   contain   

原文地址:http://www.cnblogs.com/wujufengyun/p/7121073.html

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