Given a pattern
and a string str
, find if str
follows the same pattern.
Examples:
- pattern =
"abba"
, str ="dog cat cat dog"
should return true. - pattern =
"abba"
, str ="dog cat cat fish"
should return false. - pattern =
"aaaa"
, str ="dog cat cat dog"
should return false. - pattern =
"abba"
, str ="dog dog dog dog"
should return false.
Notes:
pattern
contains only lowercase alphabetical letters, andstr
contains words separated by a single space. Each word instr
contains only lowercase alphabetical letters.- Both
pattern
andstr
do not have leading or trailing spaces. - 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_mapp2s; 8 unordered_map s2p; 9 10 vector 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 else26 if(p2s[pattern[i]] != vec[i]) return false;27 28 if(s2p.find(vec[i]) == s2p.end())29 s2p[vec[i]] = pattern[i];30 else31 if(s2p[vec[i]] != pattern[i]) return false;32 }33 return true;34 }35 };