【leetcode】【easy】【每日一题】1160. Find Words That Can Be Formed by Characters​​​​​​​

本文解析了LeetCode上一道关于字符串和字符处理的问题,通过分析如何从给定的字符集中形成有效单词,并计算所有有效单词的总长度。提供了一种使用数组记录字符频率的方法,实现了高效判断和求和。

1160. Find Words That Can Be Formed by Characters

You are given an array of strings words and a string chars.

A string is good if it can be formed by characters from chars (each character can only be used once).

Return the sum of lengths of all good strings in words.

Example 1:

Input: words = ["cat","bt","hat","tree"], chars = "atach"
Output: 6
Explanation: 
The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6.

Example 2:

Input: words = ["hello","world","leetcode"], chars = "welldonehoneyr"
Output: 10
Explanation: 
The strings that can be formed are "hello" and "world" so the answer is 5 + 5 = 10.

Note:

  1. 1 <= words.length <= 1000
  2. 1 <= words[i].length, chars.length <= 100
  3. All strings contain lowercase English letters only.

题目链接:https://leetcode-cn.com/problems/find-words-that-can-be-formed-by-characters/

 

思路

利用容器帮助记录。

class Solution {
public:
    int countCharacters(vector<string>& words, string chars) {
        if(chars.size()<0) return 0;
        int res = 0;
        int charnum[26] = {0};
        for(int i=0; i<chars.size(); ++i){
            ++charnum[chars[i]-'a'];
        }
        for(int i=0; i<words.size(); ++i){
            int wordnum[26] = {0};
            string word = words[i];
            bool isok = true;
            for(int j=0; j<word.size(); ++j){
                int idx = word[j]-'a';
                ++wordnum[idx];
                if(wordnum[idx]>charnum[idx]) {
                    isok = false;
                    break;
                }
            }
            if(isok) res += word.size();
        }
        return res;
    }
};

 

 

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值