[LeetCode] Count Words Obtained After Adding a Letter

2135. Count Words Obtained After Adding a Letter

You are given two 0-indexed arrays of strings startWords and targetWords. Each string consists of lowercase English letters only.

For each string in targetWords, check if it is possible to choose a string from startWords and perform a conversion operation on it to be equal to that from targetWords.

The conversion operation is described in the following two steps:

  1. Append any lowercase letter that is not present in the string to its end.

    • For example, if the string is “abc”, the letters ‘d’, ‘e’, or ‘y’ can be added to it, but not ‘a’. If ‘d’ is added, the resulting string will be “abcd”.
  2. Rearrange the letters of the new string in any arbitrary order.

    • For example, “abcd” can be rearranged to “acbd”, “bacd”, “cbda”, and so on. Note that it can also be rearranged to “abcd” itself.

Return the number of strings in targetWords that can be obtained by performing the operations on any string of startWords.

Note that you will only be verifying if the string in targetWords can be obtained from a string in startWords by performing the operations. The strings in startWords do not actually change during this process.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
int wordCount(vector<string>& S, vector<string>& T) {
int res(0);
unordered_set<int> s;
auto lambda = [](string& str) {
return accumulate(begin(str), end(str), 0, [](int mask, char c) -> int {
return mask |= (1 << (c - 'a'));
});
};
for (auto &str : S) {
s.insert(lambda(str));
}
for (auto &str : T) {
int mask = lambda(str);
res += any_of(begin(str), end(str), [&](char ch) -> int {
return s.count(mask ^ (1 << (ch - 'a'))); });
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/01/11/PS/LeetCode/count-words-obtained-after-adding-a-letter/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.