其他分享
首页 > 其他分享> > [Google] LeetCode 2135 Count Words Obtained After Adding a Letter

[Google] LeetCode 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:

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

Solution

由于可以进行 \(rearrange\),所以我们只需要用 \(sort\) 即可。然后用 \(map\) 来查找即可

点击查看代码
class Solution {
private:
    unordered_set<string> s;
    int ans=0;
    
public:
    int wordCount(vector<string>& sw, vector<string>& tw) {
        int n = sw.size(), m = tw.size();
        for(int i=0;i<n;i++){
            sort(sw[i].begin(), sw[i].end());
            s.insert(sw[i]);
        }
        for(int i=0;i<m;i++){
            string cur = tw[i];
            sort(cur.begin(), cur.end());
            for(int j=0;j<tw[i].size();j++){
                string tmp=cur;
                tmp.erase(tmp.begin()+j);
                if(s.find(tmp)!=s.end()){ans++;break;}
            }
        }
        return ans;
    }
};

标签:Count,Obtained,Google,letters,string,int,targetWords,abcd,startWords
来源: https://www.cnblogs.com/xinyu04/p/16654126.html