Leetcode初学——拼写单词

题目:

分析

这道题主要需要做的是,对每个单词进行检查,我利用list的contains来进行判断,存在就删除掉这个字母,不存在则继续遍历

 

代码

class Solution {
    public int countCharacters(String[] words, String chars) {
        int res=0;
        List<Character> ch=new ArrayList<>();
        for(int i=0;i<chars.length();i++){
            ch.add(chars.charAt(i));
        }


        for(int i=0;i<words.length;i++){
            List<Character> temp=new ArrayList(ch);
            int j;
            for(j=0;j<words[i].length();j++){
                if(temp.contains(words[i].charAt(j))){
                    temp.remove(temp.indexOf(words[i].charAt(j)));
                }else{
                    break;
                }
            }
            if(j==words[i].length())
                res+=j;

        }
        return res;

    }
}

 

结果

 

小结

这样的写法其实效率非常低,创建了很多个list,大量占用了内存和增加计算时间

我在题解中看到了一个非常巧妙的方法,用map的原理来做,将代码分享给大家

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)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值