[1160] LeetCode. Spell words

Topic links:

1160. spell words

Subject description:

Give you a "Glossary" (array of strings) wordsand a "alphabet" (string) chars.

If you can use charsthe "alphabet" (character) spelled out wordsin a "word" (string), then we think you've mastered the word.

Note: Each time spelling charsof each letter can only be used once.

Returns the vocabulary wordsyou master all the words and length.

Example:

Example 1:

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

Example 2:

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

prompt:

  1. 1 <= words.length <= 1000
  2. 1 <= words[i].length, chars.length <= 100
  3. All string contains only lowercase letters

Ideas:

  1. Statistics alphabet charsnumber of times each letter appears;
  2. Check the glossary wordseach word word:
    • If the wordnumber of times each letter appears all times equal to the corresponding letters appear in the vocabulary of less than 10, wordmay charsspell.
class Solution {
    public int countCharacters(String[] words, String chars) {
        int answer = 0;
        // 统计“字母表”中每个字母出现的次数
        int[] charsCount = count(chars);
        for (String word : words) {
            // 统计“词汇表”每个单词中每个字母出现的次数
            int[] wordCount = count(word);
            if (contains(charsCount, wordCount)) {
                answer += word.length();
            }
        }
        return answer;
    }

    // 统计字符串中每个字母出现的次数
    private int[] count(String str) {
        int[] counter = new int[26];
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            counter[c - 'a'] ++;
        }
        return counter;
    }

    // 检查字母表chars能否拼出单词word
    private boolean contains(int[] charsCount, int[] wordCount) {
        for (int i = 0; i < 26; i++) {
            if (charsCount[i] < wordCount[i]) {
                return false;
            }
        }
        return true;
    }
}

Guess you like

Origin www.cnblogs.com/ME-WE/p/12509146.html