前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 2135. 统计追加字母可以获得的单词数(位运算+哈希)

LeetCode 2135. 统计追加字母可以获得的单词数(位运算+哈希)

作者头像
Michael阿明
发布2022-03-10 17:58:20
3330
发布2022-03-10 17:58:20
举报

文章目录

1. 题目

给你两个下标从 0 开始的字符串数组 startWords 和 targetWords 。每个字符串都仅由 小写英文字母 组成。

对于 targetWords 中的每个字符串,检查是否能够从 startWords 中选出一个字符串,执行一次 转换操作 ,得到的结果与当前 targetWords 字符串相等。

转换操作 如下面两步所述:

  • 追加 任何 不存在 于当前字符串的任一小写字母到当前字符串的末尾。 例如,如果字符串为 “abc” ,那么字母 ‘d’、‘e’ 或 ‘y’ 都可以加到该字符串末尾,但 ‘a’ 就不行。如果追加的是 ‘d’ ,那么结果字符串为 “abcd” 。
  • 重排 新字符串中的字母,可以按 任意 顺序重新排布字母。 例如,“abcd” 可以重排为 “acbd”、“bacd”、“cbda”,以此类推。注意,它也可以重排为 “abcd” 自身。

找出 targetWords 中有多少字符串能够由 startWords 中的 任一 字符串执行上述转换操作获得。返回 targetWords 中这类 字符串的数目 。

注意:你仅能验证 targetWords 中的字符串是否可以由 startWords 中的某个字符串经执行操作获得。startWords 中的字符串在这一过程中 不 发生实际变更。

代码语言:javascript
复制
示例 1:
输入:startWords = ["ant","act","tack"], targetWords = ["tack","act","acti"]
输出:2
解释:
- 为了形成 targetWords[0] = "tack" ,可以选用 startWords[1] = "act" ,追加字母 'k' ,并重排 "actk" 为 "tack" 。
- startWords 中不存在可以用于获得 targetWords[1] = "act" 的字符串。
  注意 "act" 确实存在于 startWords ,但是 必须 在重排前给这个字符串追加一个字母。
- 为了形成 targetWords[2] = "acti" ,可以选用 startWords[1] = "act" ,追加字母 'i' ,并重排 "acti" 为 "acti" 自身。

示例 2:
输入:startWords = ["ab","a"], targetWords = ["abc","abcd"]
输出:1
解释:
- 为了形成 targetWords[0] = "abc" ,可以选用 startWords[0] = "ab" ,追加字母 'c' ,并重排为 "abc" 。
- startWords 中不存在可以用于获得 targetWords[1] = "abcd" 的字符串。
 
提示:
1 <= startWords.length, targetWords.length <= 5 * 10^4
1 <= startWords[i].length, targetWords[j].length <= 26
startWords 和 targetWords 中的每个字符串都仅由小写英文字母组成
在 startWords 或 targetWords 的任一字符串中,每个字母至多出现一次

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/count-words-obtained-after-adding-a-letter 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2. 解题

  • 将 startwords 里的单词转成 26 位 int 数字,再添加一个不存在的 bit 进去,所有的情况存到 哈希 里
  • 遍历 targetword 里的单词转成 int ,在哈希里能查到就可以转换
代码语言:javascript
复制
class Solution {
public:
    int wordCount(vector<string>& startWords, vector<string>& targetWords) {
        unordered_set<int> set;
        for(auto& s : startWords)
        {
            int num = 0;
            for(auto c : s)
                num |= 1<<(c-'a');
            for(int i = 0; i < 26; ++i)
            {
                if((num&(1<<i))==0)//添加了不存在的字母
                {
                    set.insert(num | (1<<i));
                }
            }
        }
        int ans = 0;
        for(auto& s : targetWords)
        {
            int num = 0;
            for(auto c : s)
                num |= 1<<(c-'a');
            if(set.find(num) != set.end())
                ans++;
        }
        return ans;
    }
};

460 ms 151.5 MB C++


我的CSDN博客地址 https://michael.blog.csdn.net/

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 文章目录
  • 1. 题目
  • 2. 解题
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档