当前位置:   article > 正文

leetcode刷题(4)——1160.拼写单词_有一个字符串数据word和一个字符串chars c语言

有一个字符串数据word和一个字符串chars c语言

一、题目

给你一份『词汇表』(字符串数组) 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 <= words.length <= 1000
  • 1 <= words[i].length, chars.length <= 100
  • 所有字符串中都仅包含小写英文字母

二、思路

这是一类经典题型。遇到字符串仅包含小写(或者大写)英文字母的题,都可以试着考虑构造长度为 26 的数组。这样,数组每个位置分别代表一个字母,统计出字母出现的次数,方便后面问题的解决。

本题中,既要统计“字母表”中字母出现的次数,也要统计单词中字母出现的次数。如果字母表中字母出现的次数大于等于单词中每种字母出现的次数,那么这个单词就可以由字母表拼写出来。

以字母表 “atach” 和 词汇 “cat” 为例,整个过程图示如下:
在这里插入图片描述
由图可知,词汇 “cat” 可以由字母表拼出,则将 “cat” 的长度加到结果中。

三、代码

class Solution {
    public int countCharacters(String[] words, String chars) {
        int[] charCount = count(chars);// 统计字母表中的字母
        int result = 0;// 拼写的结果
        for(int i = 0; i < words.length; i++){
            int[] wordCount = count(words[i]);
            if(contains(charCount, wordCount)){
                result += words[i].length();
            }
        }
        return result;
    }

    // 检查字母表中字母出现的次数是否大于等于词汇表中单词的字母出现的次数
    public boolean contains(int[] charCount, int[] wordCount){
        for(int i = 0; i < 26; i++){
            if(charCount[i] < wordCount[i]){
                return false;
            }
        }
        return true;
    }

    // 统计一个字符串中 26 个字母出现的次数
    public int[] count(String s){
        int[] countRes = new int[26];
        for(int i = 0; i < s.length(); i++){
            countRes[(int)(s.charAt(i) - 'a')] += 1;
        }
        return countRes;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/705355
推荐阅读
相关标签
  

闽ICP备14008679号