美文网首页
leetcode-Array篇easy难度之字符串组合分析

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

作者: 茉莉清可乐对奶茶i | 来源:发表于2020-11-10 14:37 被阅读0次

    关键词

    字符串

    题目描述

    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;
        }
    }
    

    其他人优秀的解法

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

    相关文章

      网友评论

          本文标题:leetcode-Array篇easy难度之字符串组合分析

          本文链接:https://www.haomeiwen.com/subject/jfljbktx.html