LeetCode 290 Word Pattern
Problem:
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:
- 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:
You may assume pattern
contains only lowercase letters, and str
contains lowercase letters separated by a single space.
Summary:
判断所给字符串str中单词的形式与pattern中是否相符。
Solution:
以key为pattern中的char,value为str中的单词构成Hash Table,每加进一个新单词,判断原来若存在相同key的单词是否与新单词相同。
最终需排除不同key,value相同的情况。
1 class Solution { 2 public: 3 bool wordPattern(string pattern, string str) { 4 vector<string> s; 5 unordered_map<char, string> m; 6 7 int flag = 0; 8 for (int i = 0; i < str.size(); i++) { 9 if (str[i] == ' ') { 10 s.push_back(str.substr(flag, i - flag)); 11 flag = i + 1; 12 } 13 } 14 s.push_back(str.substr(flag, str.size() - flag)); 15 16 if (pattern.size() != s.size()) { 17 return false; 18 } 19 20 for (int i = 0; i < pattern.size(); i++) { 21 if (m[pattern[i]] == "") { 22 m[pattern[i]] = s[i]; 23 } 24 else if (m[pattern[i]] != s[i]){ 25 return false; 26 } 27 } 28 29 for (unordered_map<char, string>::iterator i = m.begin(); i != m.end(); i++) { 30 for (unordered_map<char, string>::iterator j = m.begin(); j != m.end(); j++) { 31 if (i->second == j->second && i->first != j->first) { 32 return false; 33 } 34 } 35 } 36 37 return true; 38 } 39 };