0
点赞
收藏
分享

微信扫一扫

leetcode 1160.拼写单词

邯唐情感 2022-05-02 阅读 34

leetcode 1160.拼写单词

文章目录

一、题目

1.题目描述

给你一份『词汇表』(字符串数组) words 和一张『字母表』(字符串) chars

假如你可以用 chars 中的『字母』(字符)拼写出 words 中的某个『单词』(字符串),那么我们就认为你掌握了这个单词。

注意:每次拼写(指拼写词汇表中的一个单词)时,chars 中的每个字母都只能用一次。

返回词汇表 words 中你掌握的所有单词的 长度之和

示例 1:

输入:words = ["cat","bt","hat","tree"], chars = "atach"
输出:6
解释: 
可以形成字符串 "cat""hat",所以答案是 3 + 3 = 6

示例 2:

输入:words = ["hello","world","leetcode"], chars = "welldonehoneyr"
输出:10
解释:
可以形成字符串 "hello""world",所以答案是 5 + 5 = 10

提示:

  1. 1 <= words.length <= 1000
  2. 1 <= words[i].length, chars.length <= 100
  3. 所有字符串中都仅包含小写英文字母

2.基础框架

C++基础框架代码如下:

int countCharacters(vector<string>& words, string chars) {
}

3.解题思路

  • 题目分析

    用hash数组记录字母表的字母,对词汇表中的每一组字符串一一进行比对是否hash数组中存在对应的元素,并且满足个数能够拼写出完整的字母。因为需要记录重复的单词,所以会修改到hash数组中同一元素的个数,所以用到临时数组tmp对hash数组进行复制。

  • 实现代码:

    int countCharacters(vector<string>& words, string chars) {
        vector<int> rec(26);
        int i, j;
        for (i = 0; i < chars.size(); ++i)
            ++rec[chars[i] - 'a'];
        int ans = 0;
        for (i = 0; i < words.size(); ++i)
        {
            bool flag = true;
            vector<int> tmp = rec;
            for (j = 0; j < words[i].size(); ++j)
            {
                if (tmp[words[i][j] - 'a'] <= 0)
                {
                    flag = false;
                    break;
                }
                --tmp[words[i][j] - 'a'];
            }
            if (flag == true)
                ans += words[i].size();
        }
        return ans;
    }
    
举报

相关推荐

0 条评论