[LeetCode] Words Within Two Edits of Dictionary

2452. Words Within Two Edits of Dictionary

You are given two string arrays, queries and dictionary. All words in each array comprise of lowercase English letters and have the same length.

In one edit you can take a word from queries, and change any letter in it to any other letter. Find all words from queries that, after a maximum of two edits, equal some word from dictionary.

Return a list of all words from queries, that match with some word from dictionary after a maximum of two edits. Return the words in the same order they appear in queries.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
vector<string> twoEditWords(vector<string>& queries, vector<string>& dictionary) {
vector<string> res;
for(auto q : queries) {
bool pass = false;
for(auto d : dictionary) {
int cnt = 0;
for(int i = 0; i < d.length() and cnt < 3; i++) if(d[i] != q[i]) cnt++;
if(cnt <= 2) pass = true;
if(pass) break;
}
if(pass) res.push_back(q);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/30/PS/LeetCode/words-within-two-edits-of-dictionary/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.