1160. 拼写单词『简单』

题目来源于力扣(LeetCode

一、题目

1160. 拼写单词

题目相关标签:数组、哈希表

提示:

  • 1 <= words.length <= 1000
  • 1 <= words[i].length, chars.length <= 100
  • 所有字符串中都仅包含小写英文字母

二、解题思路

  1. 字符串 chars 中各出现的字符元素进行哈希数组的映射,键为数组索引,值为字符出现的次数

  2. 遍历 words 数组,对数组中的单词也进行哈希数组的映射

  3. 将两个哈希数组进行遍历比较,判断 word 字符串中的字符是否都在 chars 字符串中存在,即 word 字符串的哈希映射元素都小于或等于 chars 字符串的哈希映射数组元素

三、代码实现

public static int countCharacters(String[] words, String chars) {
    int[] hashArr = new int[26];
    // 将 chars 字符串中的各字符元素出现的次数映射到 hashArr 数组中
    for (char i : chars.toCharArray()) {
        hashArr[i - 'a'] += 1;
    }
    int ans = 0;
    
    for (int i = 0; i < words.length; i++) {
        int[] arr = new int[26];
        char[] chs = words[i].toCharArray();
        // 将 word 字符串中的各字符元素出现的次数映射到 arr 数组中
        for (int j = 0; j < chs.length; j++) {
            arr[chs[j] - 'a'] += 1;
        }
        int k = 0;
        // 遍历两个哈希数组,判断 word 中的字母能否都在 chars 中存在,即小于等于,大于时即不满足
        for (; k < hashArr.length; k++) {
            if (arr[k] > hashArr[k]) {
                break;
            }
        }
        // k 能走到最后说明单词 word 中的字母都在 chars 中存在
        ans += (k == hashArr.length) ? chs.length : 0;
    }
    return ans;
}

四、执行用时

五、部分测试用例

public static void main(String[] args) {
    String[] words = {"cat", "bt", "hat", "tree"};
    String chars = "atach";  // output:6

//    String[] words = {"hello", "world", "leetcode"};
//    String chars = "welldonehoneyr";  // output:10
    
    int result = countCharacters(words, chars);
    System.out.println(result);
}
posted @ 2020-06-09 21:05  知音12138  阅读(246)  评论(0编辑  收藏  举报