290. Word Pattern(技巧:記錄當前位置來判斷兩個字串是否符合)
阿新 • • 發佈:2018-12-30
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"
- 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.
1.我的答案
這裡有個技巧:就是對兩個字串,記錄每個字元當前位置,當前比較的字元的之前位置相同,則將當前位置記錄;若比較的字元的之前位置不同,則不符合模式;若之前沒出現過,則將該字元的位置記為當前位置。
類似的題目為:205. Isomorphic Strings
以下為我的程式碼:
class Solution { public: bool wordPattern(string pattern, string str) { map<char,int>map_p; map<string,int>map_s; vector<string> vec; string s = ""; int len_pat = pattern.size(); for(int i = 0; i < str.size(); i++){ if(str[i] == ' '){ vec.push_back(s); s = ""; continue; } s += str[i]; } vec.push_back(s); int len_str = vec.size(); if(len_pat != len_str) return false; for(int k = 0; k < len_str; k++){ if(map_p.find(pattern[k]) == map_p.end()) map_p[pattern[k]] = k; if(map_s.find(vec[k]) == map_s.end()) map_s[vec[k]] = k; if(map_p[pattern[k]] == map_s[vec[k]]){ map_p[pattern[k]] = k; map_s[vec[k]] = k; }else return false; } return true; } };
2.大神的程式碼 真是膜拜啊啊!
用i+1避免掉0產生的歧義性(雖然我現在還是不明白為什麼要這麼做)
bool wordPattern(string pattern, string str) {
map<char, int> p2i;
map<string, int> w2i;
istringstream in(str);
int i = 0, n = pattern.size();
for (string word; in >> word; ++i) {
if (i == n || p2i[pattern[i]] != w2i[word])
return false;
p2i[pattern[i]] = w2i[word] = i + 1;
}
return i == n;
}