-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathLC0890.cpp
More file actions
executable file
·38 lines (32 loc) · 807 Bytes
/
LC0890.cpp
File metadata and controls
executable file
·38 lines (32 loc) · 807 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/*
Problem Statement: https://leetcode.com/problems/find-and-replace-pattern/
Time: O(m • n)
Space: O(m • n)
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
*/
class Solution {
public:
vector<string> findAndReplacePattern(vector<string>& words, string pattern) {
int m = words.size();
vector<string> matches;
for (string& word: words)
if (match(word, pattern))
matches.push_back(word);
return matches;
}
bool match(string& word, string& pattern) {
int n = pattern.size();
unordered_set<char> seen;
unordered_map<char, char> mp;
for (int i = 0; i < n; i++) {
if (!mp.count(pattern[i])) {
if (!seen.insert(word[i]).second)
return false;
mp[pattern[i]] = word[i];
}
if (mp[pattern[i]] != word[i])
return false;
}
return true;
}
};