Leetcode 290 Word Pattern STL

Leetcode 205 Isomorphic Strings的进阶版

这次是词组字符串和匹配字符串相比较是否一致

请使用map来完成模式统计

 1 class Solution {
 2 public:
 3     bool wordPattern(string pattern, string str) {
 4         map<char,int> mp;
 5         map<string,int> ms;
 6         vector<int> p,s;
 7         int cnt = 0;
 8         for(string::size_type i = 0; i < pattern.size(); ++i){
 9             if(mp.find(pattern[i]) == mp.end()){
10                 mp[pattern[i]] = cnt++;
11                 p.push_back(mp[pattern[i]]);
12             }
13             else p.push_back(mp[pattern[i]]);
14         }
15         int a = 0, b = 0;
16         cnt = 0;
17         while((b = str.find(" ", a)) != string::npos){
18             string t = str.substr(a, b - a);
19             if(ms.find(t) == ms.end()){
20                 ms[t] = cnt++;
21                 s.push_back(ms[t]);
22             }
23             else s.push_back(ms[t]);
24             a = b + 1;
25         }
26         b = str.size();
27         string t = str.substr(a, b - a);
28         if(ms.find(t) == ms.end()){
29             ms[t] = cnt++;
30             s.push_back(ms[t]);
31         }
32         else s.push_back(ms[t]);
33         if(p.size() != s.size()) return false;
34         for(vector<int>::size_type i = 0; i < s.size(); ++i){
35             if(s[i] != p[i]) return false;
36         }
37         return true;
38     }
39 };

 

posted @ 2016-03-17 21:09  Breeze0806  阅读(135)  评论(0编辑  收藏  举报