---
# System prepended metadata

title: 2135. Count Words Obtained After Adding a Letter
tags: [Leetcode, Bit Manipulation, Medium]

---

# 2135. Count Words Obtained After Adding a Letter
###### tags: `Leetcode` `Medium` `Bit Manipulation`
Link: https://leetcode.com/problems/count-words-obtained-after-adding-a-letter/
## 思路
要注意题里的限定条件是每个word里面都没有重复的字母 因此可以用bit mask
对于一个长度为n的targetword来说 我们需要在startword里面找到一个恰好有n-1个targetword里面的字母的word
## Code
```java=
class Solution {
    public int wordCount(String[] startWords, String[] targetWords) {
        int ans = 0;
        Set<Integer> set = new HashSet<>();
        for(String w:startWords) set.add(bitmask(w));
        for(String w:targetWords){
            int mask = bitmask(w);
            for(int i=0; i<26; i++){
                if(((mask>>i)&1)!=1) continue;
                if(set.contains(mask-(1<<i))){
                    ans++;
                    break;
                }
            }
        }
        return ans;
    }
    private int bitmask(String word){
        int mask = 0;
        for(int i=0; i<word.length(); i++){
            mask += 1<<(word.charAt(i)-'a');
        }
        return mask;
    }
}
```