Find and Replace Pattern LeetCode solution in C++

1
// ��If you Like the repository don't foget to star & fork the repository��
2
class Solution {
3
public:
4
vector<int> found_Pattern(string pattern) {
5
// if string is empty return empty vector.
6
if (pattern.size() == 0) return {};
7

8
vector<int> v;
9

10
// ind variable for keeping track of unique characters
11
int ind = 0;
12

13
unordered_map<char, int> mp;
14
for (int i = 0; i < pattern.size(); ++i) {
15
// if character not present in map, insert the char with an index,
16
// increment index because for next unique character the index should be
17
// differnt.
18
if (mp.find(pattern[i]) == mp.end()) {
19
mp.insert({pattern[i], ind++});
20
// also push the index to v(numeric pattern vector)
21
// mp[pattern[i]] gives the key to that character, here key is ind(which
22
// we are giving to every unique character)
23
v.push_back(mp[pattern[i]]);
24
} else {
25
// if char is already in map than push index mapped to that character
26
// into the vector
27
v.push_back(mp[pattern[i]]);
28
}
29
}
30
// return numeric pattern
31
return v;
32
}
33
vector<string> findAndReplacePattern(vector<string> &words, string pattern) {
34
// store numeric patten of Pattern string in v
35
vector<int> v = found_Pattern(pattern);
36

37
int n = words.size();
38
vector<string> ans;
39

40
// iterating and comparing pattern of each word with v(numeric pattern of
41
// Pattern)
42
for (int i = 0; i < n; ++i) {
43
vector<int> pattern_word = found_Pattern(words[i]);
44

45
// if matched add words[i] to answer vector
46
if (v == pattern_word) ans.push_back(words[i]);
47
}
48

49
return ans;
50
}
51
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0