Word Pattern

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

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:

  1. patterncontains only lowercase alphabetical letters, and str contains words separated by a single space. Each word in str contains only lowercase alphabetical letters.
  2. Both pattern and str do not have leading or trailing spaces.
  3. Each letter in pattern must map to a word with length that is at least 1.

Runtime: 0ms

 1 class Solution {
 2 public:
 3     bool wordPattern(string pattern, string str) {
 4         if(pattern.empty() && str.empty()) return true;
 5         if(pattern.empty() || str.empty()) return false;
 6         
 7         unordered_map<char, string> p2s;
 8         unordered_map<string, char> s2p;
 9         
10         vector<string> vec;
11         int start = 0, end = 0;
12         while(end < str.size()){
13             while(end < str.size() && str[end] != ' ')
14                 end++;
15             vec.push_back(str.substr(start, end - start));
16             start = end + 1;
17             end = start;
18         }
19         
20         if(pattern.length() != vec.size()) return false;
21         
22         for(int i = 0; i < pattern.size(); i++){
23             if(p2s.find(pattern[i]) == p2s.end())
24                 p2s[pattern[i]] = vec[i];
25             else
26                 if(p2s[pattern[i]] != vec[i]) return false;
27                 
28             if(s2p.find(vec[i]) == s2p.end())
29                 s2p[vec[i]] = pattern[i];
30             else
31                 if(s2p[vec[i]] != pattern[i]) return false;
32         }
33         return true;
34     }
35 };
原文地址:https://www.cnblogs.com/amazingzoe/p/4859490.html