GuilinDev

Lc1160

05 August 2008

1160. Find Words That Can Be Formed by Characters

你得到一个字符串数组和一个字符串字符。

如果字符串可以由 chars 中的字符组成(每个字符只能使用一次),则它是好的。

返回单词中所有好的字符串的长度总和。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
    public int countCharacters(String[] words, String chars) {
        if (words == null || words.length == 0 || chars == null || chars.length() == 0) return 0;
        int resultCount = 0;
        for (String str : words) {
            if (canForm(str, chars)) resultCount += str.length();
        }

        return resultCount;
    }

    public boolean canForm(String word, String chars) {
        int[] chArr = new int[26];
        for (int i = 0; i < chars.length(); i++) {
            chArr[chars.charAt(i) - 'a']++;
        }

        for (int i = 0; i < word.length(); i++) {
            if (chArr[word.charAt(i) - 'a'] <= 0) return false;
            chArr[word.charAt(i) - 'a']--;
        }

        return true;
    }
}