3月打卡活动第17天 LeetCode第1160题:拼写单词(简单)

3月打卡活动第17天 LeetCode第1160题:拼写单词(简单)

  • 题目:给你一份『词汇表』(字符串数组) words 和一张『字母表』(字符串) chars。假如你可以用 chars 中的『字母』(字符)拼写出 words 中的某个『单词』(字符串),那么我们就认为你掌握了这个单词。注意:每次拼写时,chars 中的每个字母都只能用一次。返回词汇表 words 中你掌握的所有单词的 长度之和。
    在这里插入图片描述
  • 解题思路:逐一对比,有点麻烦。
class Solution {
    public int countCharacters(String[] words, String chars) {
        int ans = 0;
        HashMap<String,Integer> cc = new HashMap<>();
        for(int i=0;i<chars.length();i++){
            String c = chars.charAt(i)+"";
            if(cc.containsKey(c)){
                cc.put(c,cc.get(c)+1);
            }else{
                cc.put(c,1);
            }
        }
        for(int i=0;i<words.length;i++){
            HashMap<String,Integer> newC = new HashMap<>();
            newC.putAll(cc);
            String ss = words[i];
            if(ss.length()<=chars.length()){
                int j=0;
                while(j<ss.length()){
                    String s = ss.charAt(j)+"";
                    if(newC.containsKey(s) && newC.get(s)>0){
                        newC.put(s,newC.get(s)-1);
                        j++;
                    }else{
                        break;
                    }
                }
                if(j==ss.length()) ans+=ss.length();
            }
        }
        return ans;
    }
}

在这里插入图片描述

  • 题解做法:构造一个长度为26的数组,记录每个字母出现的次数。省去了HashMap简洁很多。
class Solution {
    public int countCharacters(String[] words, String chars) {
        int[] c = new int[26];
        for(char cc : chars.toCharArray()) {
            c[(int)(cc - 'a')] += 1;
        }
        int res = 0;
        a: for(String word : words) {
            int[] w = new int[26];
            for(char ww : word.toCharArray()) {
                w[(int)(ww - 'a')] += 1;
            }
            for(int i=0; i<26; i++) {
                if(w[i] > c[i]) {
                    continue a;
                }
            }
            res += word.length();
        }
        return res;
    }
}

作者:pendygg
链接:https://leetcode-cn.com/problems/find-words-that-can-be-formed-by-characters/solution/ji-de-di-yi-ci-kan-bie-ren-yong-int26de-shi-hou-be/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

在这里插入图片描述

发布了100 篇原创文章 · 获赞 12 · 访问量 2351

猜你喜欢

转载自blog.csdn.net/new_whiter/article/details/104913980