leetcode-Array篇easy难度之字符串组合分析

关键词

字符串

题目描述

https://leetcode.com/problems/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 <= words.length <= 1000
1 <= words[i].length, chars.length <= 100
All strings contain lowercase English letters only.

博主提交的代码

class Solution {
    public int countCharacters(String[] words, String chars) {
        int result = 0;
        Map<Character,Integer> resource = new HashMap<>(32);
        for(char eachChar: chars.toCharArray()){
            resource.put( eachChar, resource.getOrDefault(eachChar,0)+1);
        }
        for(String eachWord: words){
            Map<Character,Integer> now = new HashMap<>(32);
            for(char eachChar: eachWord.toCharArray()){
                now.put( eachChar, now.getOrDefault(eachChar,0)+1);
            }
            if(now.size() > resource.size()){
                continue ;
            }
            boolean findIt = true;
            for(Map.Entry<Character,Integer> entry: now.entrySet()){
                if( resource.get(entry.getKey()) == null || resource.get(entry.getKey()) < entry.getValue()){
                    findIt = false;
                    break;
                }
            }
            if(findIt){
                result+= eachWord.length();
            }
            
        }
        return result;
    }
}

其他人优秀的解法

持续关注吧,没有发现太好的

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容