题目中有很关键的条件:
1:每个字符串都仅由小写字母组成——>用int作为hash足够了。
2:任一字符串中,每个字母至多出现一次——>标记是否存在可以用hash
难点:
1:对任意一个在targetwords中的字符串,在startwords数组中找能形成它的字符串,用O(n)?数据范围是5×10的4次方,肯定会超时,于是尝试删除该字符串中的每个字符,看一下删除后的字符串在startwords中是否有对应的(O(n)降低到O(常数,26))。
2:在跟startwords中是否有对应的字符串时,一个一个比会达到O(n)的复杂度因此采用hash把startwords中的每个字符串保存下来,在startwords中查找时O(n)降到O(1)的复杂度,
3:对比两个键时,实际在比较两个hash,会达到O(常数,26)的复杂度,由于只有26个小写字母且最多只存在一次,因此可以用2进制来表示hash,比较键的复杂度O(常数,26)降到O(1)
正解思路:hash(二进制)
class Solution {
public:
int wordCount(vector<string>& startWords, vector<string>& targetWords) {
unordered_set<int> hash; //
for (auto& s : startWords) {
int a = 0;
for (auto& ch: s) {
a |= (1 << (ch - 'a'));
}
hash.insert(a);
}
int ans = 0;
for (auto& s : targetWords) {
int a = 0;
for (auto& ch : s) {
a |= (1 << (ch - 'a'));
}
for (auto& ch :s) { //
if (hash.count(a ^ (1 << (ch - 'a')))) {
ans++;break; //
}
}
}
return ans;
}
};
代码上的难点:
1:删除2进制中每个1时,从二进制上不好做,可以通过枚举字符找2进制的每个位置 用异或翻转某一位。
2:翻转某个二进制值,用异或
3:删除某一个字符,找到一个符合之后,要break掉,不然会对同一个满足的字符串ans可能会增加多次。