LeetCode 1160. Find Words That Can Be Formed by Characters (Java版; Easy)

welcome to my blog

LeetCode 1160. Find Words That Can Be Formed by Characters (Java版; Easy)

题目描述

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.

第一次做; 核心: 1)哈希表map记录记录chars中各个字符出现的次数, 然后遍历words, 每一次使用一个新的哈希表map2记录当前遍历到的单词word中的各个字符出现的次数, 遍历map2, 对于当前key, 如果key在map中出现的次数大于等于map2中出现的次数, 说明该字符满足条件, 否则不满足条件

class Solution {
    public int countCharacters(String[] words, String chars) {
        HashMap<Character, Integer> map = new HashMap<>();
        for(int i=0; i<chars.length(); i++){
            char ch = chars.charAt(i);
            map.put(ch, map.getOrDefault(ch, 0)+1);
        }

        int res=0;
        boolean flag=true;
        for(String word : words){
            HashMap<Character, Integer> map2 = new HashMap<>();
            for(int i=0; i<word.length(); i++){
                char ch = word.charAt(i);
                map2.put(ch, map2.getOrDefault(ch,0)+1);
            }
            for(Map.Entry<Character,Integer> entry : map2.entrySet()){
                char ch = entry.getKey();
                //这里是大于等于, 别犯蠢..
                if(map.getOrDefault(ch,0) >= map2.get(ch)){
                    continue;
                }
                flag=false;
                break;
            }
            if(flag==false){
                flag=true;
                continue;
            }
            res += word.length();
        }
        return res;
    }
}
发布了605 篇原创文章 · 获赞 152 · 访问量 21万+

猜你喜欢

转载自blog.csdn.net/littlehaes/article/details/104916115
今日推荐