LeetCode 1160. 拼写单词

100 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第22天,点击查看活动详情

1.描述

1160. 拼写单词 - 力扣(LeetCode)

给你一份『词汇表』(字符串数组) words 和一张『字母表』(字符串) chars

假如你可以用 chars 中的『字母』(字符)拼写出 words 中的某个『单词』(字符串),那么我们就认为你掌握了这个单词。

注意:每次拼写(指拼写词汇表中的一个单词)时,chars 中的每个字母都只能用一次。

返回词汇表 words 中你掌握的所有单词的 长度之和。

 

示例 1:

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

示例 2:

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

提示:

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

2.分析

  1. Hash chars;
  2. Hash word in words;
  3. 然后在遍历words的时候依次去通过Hash保存的value来对比, 如果word的所有字母个数都<chars中的所有字母, 则才能够满足需求;
  4. 中途使用tempLen来和word的length进行对比, 来确认是不是所有字母都满足需求;
  5. 返回resultLen;

3.AC代码

# @param {String[]} words
# @param {String} chars
# @return {Integer}
def count_characters(words, chars)
    resultLen = 0 # Use for return the result
    # puts get_hash(chars)
    cntChars = get_hash(chars)
    for word in words do
        # reset this is for comparing to word.length, make sure all the alphabetic in cntWord is in cntChars
        tempLen = 0 
        # puts get_hash(word)
        cntWord = get_hash(word)
        cntWord.each do |key, value|
            # If the alphabetic in cntWord is less than or equal to cntChars, 
            # that means can not spell it by.
            if cntWord[key] <= cntChars[key]
                tempLen += cntWord[key]
            end 
        end
        if word.length == tempLen
            resultLen += tempLen
        end 
    end 
    resultLen
end

# This def is for hash the alphebatic.
def get_hash(stringToHash)
    # saving Hash
    cnt = Hash.new(0)
    # String to array later can use in for loop
    stringToHash = stringToHash.split("")
    for i in stringToHash do
        # key value Hash, later use
        cnt[i] += 1
        # cnt["John"] += 2
        # cnt["Anna"] += 4
        # cnt # => {"Anna" => 7, "John" => 2}
        # cnt["Mario"] #=> 0
    end 
    return cnt
end


参考

#1160 拼写单词 两个数组对比进行求解 - 拼写单词 - 力扣(LeetCode)