0317-2020-LEETCODE-1160- spell words

Is a very good idea, use int [26] to store the number of occurrences of the dictionary 26 letters of the alphabet map [c - 'a'] ++; then two successive comparison map, a word regardless of cycle 26 times (subMap [ j] == 0 would not compare).

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;
    }

Write your own time and effort, with the list kept, each time after the end of the spell, restore the original list of the current list. Analyzing each spelling need exists or not, there is no direct break; letter exists, comparison cycle continues.

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;
    }
Published 98 original articles · won praise 0 · Views 2194

Guess you like

Origin blog.csdn.net/weixin_43221993/article/details/104915209