[LeetCode] Camelcase Matching

1023. Camelcase Matching

Given an array of strings queries and a string pattern, return a boolean array answer where answer[i] is true if queries[i] matches pattern, and false otherwise.

A query word queries[i] matches pattern if you can insert lowercase English letters pattern so that it equals the query. You may insert each character at any position and you may not insert any characters.

  • two pointer solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
bool match(string& q, string& p) {
int i, j;
for(i = 0, j = 0; i < q.length() and j < p.length(); i++) {
if(q[i] == p[j]) j++;
else if('A' <= q[i] and q[i] <= 'Z') return false;
}
return j == p.length();
}
public:
vector<bool> camelMatch(vector<string>& queries, string pattern) {
vector<bool> res;
for(auto& q : queries) {
res.push_back(match(q, pattern));
}
return res;
}
};

  • trie solution
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
39
40
41
42
43
44
45
46
47
48
49
class Trie {
unordered_map<char, Trie*> next;
int eof;
bool isNEOF(char c) {
return ('A' <= c and c <= 'Z') or ('a' <= c and c <= 'z');
}
public:
Trie(): eof(-1){}

void insert(int idx, const char* word) {
if(!isNEOF(*word)) eof = idx;
else {
if(!next.count(*word)) next[*word] = new Trie();
next[*word]->insert(idx, word+1);
}
}

void match(const char* pattern, vector<bool>& res) {
if(!isNEOF(*pattern)) {
if(eof != -1) res[eof] = true;
for(char c = 'a'; c <= 'z'; c++) {
if(next.count(c)) {
next[c]->match(pattern, res);
}
}
} else {
if('A' <= *pattern and *pattern <= 'Z' and next.count(*pattern)) {
next[*pattern]->match(pattern + 1, res);
}
for(char c = 'a'; c <= 'z'; c++) {
if(next.count(c)) {
next[c]->match(c == *pattern ? pattern + 1 : pattern, res);
}
}
}
}
};
class Solution {
public:
vector<bool> camelMatch(vector<string>& queries, string pattern) {
vector<bool> res(queries.size(), false);
Trie* trie = new Trie();
for(int i = 0; i < queries.size(); i++) {
trie->insert(i, queries[i].c_str());
}
trie->match(pattern.c_str(), res);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/04/PS/LeetCode/camelcase-matching/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.