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 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| public class GetChar2 { public static void main(String[] args) { String[] words = {"hello","world","leetcode"}; String chars = "welldonehoneyr"; System.out.println(countCharacters(words,chars)); }
//1.统计字母表chars中26个字母个数 //2.统计词汇表中单个词汇words[i]中26个字母个数 //3.单个词汇中字母个数与字母表中字母个数比较 public static int countCharacters(String[] words, String chars) { //字母表26个字母的个数 int sum = 0; int[] chars1 = new int[26]; for (char c : chars.toCharArray()) { chars1[c - 'a']++; }
for (String str : words) { int[] chars2 = new int[26]; //每个单词26个字母的个数 for (char strch : str.toCharArray()) { chars2[strch - 'a']++; } //System.out.println(Arrays.toString(chars2)); boolean flag = true; //比较单词和字母表的26个字母数量的大小 for (int i = 0; i < chars2.length; i++) { if (chars2[i] > chars1[i]){ flag = false; break; } } if (flag){ sum += str.length(); } } return sum; } }
|