leetcode#1160 词汇表中拼写字符串

力扣#1160 拼写单词


题目要求:给你一份『词汇表』(字符串数组) words 和一张『字母表』(字符串) chars。
假如你可以用 chars 中的『字母』(字符)拼写出 words 中的某个『单词』(字符串),那么我们就认为你掌握了这个单词。
注意:每次拼写(指拼写词汇表中的一个单词)时,chars 中的每个字母都只能用一次。
返回词汇表 words 中你掌握的所有单词的 长度之和。

输入:words = ["cat","bt","hat","tree"], chars = "atach"
输出:6
解释: 
可以形成字符串 "cat""hat",所以答案是 3 + 3 = 6。

输入:words = ["hello","world","leetcode"], chars = "welldonehoneyr"
输出:10
解释:
可以形成字符串 "hello""world",所以答案是 5 + 5 = 10

题目思路:首先必定是要对words数组进行遍历的,而且还需要两个for循环,第二个循环里面需要检查单词的字母是否在chars字符串里面出现,那么思路就可以在这里进行优化,爆破的思路就是再用一个循环判断字母是否出现在chars里面,这种复杂度就会太高。不如直接用一个哈希表储存chars里面的,这样查询的时候复杂度就可以是O(1)。
总的时间复杂度就会是O(n^2)


代码:

import java.util.HashMap;
public class HelloWorld {
    private String[] words;
    private String chars;
    public static void main(String[] args) {
        String[] words = {"cat","bt","hat","tree"};
        String chars = "atach";
        HashMap<String , Integer> kv = new HashMap<String, Integer>();
        //char[] chars1 = chars.toCharArray();
        for (int i = 0; i< chars.length(); ++i){
            System.out.println(chars.substring(i,i+1));
            if(kv.containsKey(chars.substring(i,i+1))){
                kv.replace(chars.substring(i,i+1), kv.get(chars.substring(i,i+1))+1);
            }
            else{
                kv.put(chars.substring(i,i+1), 1);
            }
        }
        System.out.println(kv);
        int sum  = 0;
        for(int i = 0; i< words.length; ++i){
            HashMap<String , Integer> temp = new HashMap<String, Integer>();
            temp.putAll(kv);
            //System.out.println(temp);
            boolean flag = false;
            int j;
            //String word = words[i];
            for(j = 0; j<words[i].length(); ++j){
                if((temp.containsKey(words[i].substring(j,j+1))) && (temp.get(words[i].substring(j,j+1)) != 0)){
                    //int n = temp
                    temp.replace(words[i].substring(j,j+1), temp.get(words[i].substring(j,j+1))-1);
                    flag = true;
                }else{
                    flag = false;
                    break;
                }
            }
            if(flag){
                System.out.println(words[i]);
            }
            sum += flag?j:0;
        }
        System.out.println(sum);
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值