890. Find and Replace Pattern

ss
May 21, 2021

--

簡單來說, 就是用一個map 紀錄, 紀錄出現過的字母, 如果再重複被map access, 就檢查是不是原本檢查那個, 另外也要再用一個set紀錄被記錄過的人

class Solution {
public:
vector<string> findAndReplacePattern(vector<string>& words, string pattern) {
vector<string> res;
for(auto word: words){
unordered_map<char, char> m;
unordered_set<char> st;
int i = 0;
bool flag = true;
for(; i < word.size();i++){
if(!m.count(pattern[i])){
if(st.count(word[i])){
flag = false;
break;
}
m[pattern[i]] = word[i];
st.insert(word[i]);
}else{
if(m[pattern[i]] != word[i]){
flag =false;
break;
};
}
}
if(flag) res.push_back(word);
}
return res;
}
};

李哥的做法果然還是精闢, 先是用一個map, 紀錄字母出現的順序, 例如

caa->122, 像這樣, 再把數字轉乘字母

122->abb

倘若兩邊轉出來的字串一樣, patternn就一樣了

class Solution {
public:
string check(string s){
unordered_map<char, int> m;
for(auto c: s){
if(!m.count(c)){
m[c] = m.size();
}
}
string res;
for(auto c: s){
res += m[c] + 'a';
}
return res;
}
vector<string> findAndReplacePattern(vector<string>& words, string pattern) {
vector<string > res;
for(auto word: words){
if(check(word) == check(pattern)) res.push_back(word);
}
return res;
}
};

--

--

ss
ss

No responses yet