0317-2020-LEETCODE-1160-拼写单词

非常好的一个思想就是,用int[26]来存储字典里26个英文字母的出现次数map[c - ‘a’]++;然后逐次比较两个map,一个单词循环26次计较(subMap[j] == 0就不用比较了)。

public int countCharacters1(String[] word,String chars){
        int[] map = new int[26];
        for (char c : chars.toCharArray()){
            map[c - 'a']++;
        }
        int res = 0;
        for (int i = 0; i < word.length; i++) {
            int[] subMap = new int[26];
            for (char c : word[i].toCharArray()) {
                subMap[c - 'a']++;
            }
            for (int j = 0; j < 26; j++) {
                if (map[j] < subMap[j]){
                    break;
                }
                if (j == 25){
                    res += word[i].length();
                }
            }
        }
        return res;
    }

自己写的费时费力,用的list存,每次拼写结束以后,恢复当前的list的初始的list。每次拼写需要判断存不存在,不存在直接break; 字母存在的话,就继续循环比较。

public int countCharacters(String[] words, String chars) {
        if (chars == null || chars.length() == 0){
            return 0;
        }
        char[] array = chars.toCharArray();
        ArrayList<Character> list = new ArrayList<>();
        for (int i = 0; i < array.length; i++) {
            list.add(array[i]);
        }
        ArrayList<Character> subList = new ArrayList<>();
        int count = 0;
        for (int i = 0; i < words.length; i++) {
            subList.clear();
            subList.addAll(list);
            for (int j = 0; j < words[i].length(); j++) {
                if (subList.contains(words[i].charAt(j))){
                    subList.remove((Character) words[i].charAt(j));
                } else {
                    break;
                }
                if (j == words[i].length() - 1){
                    count += words[i].length();
                }
            }
        }
        return count;
    }
发布了98 篇原创文章 · 获赞 0 · 访问量 2194

猜你喜欢

转载自blog.csdn.net/weixin_43221993/article/details/104915209