|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +# 1160. Find Words That Can Be Formed by Characters |
| 4 | +# Easy |
| 5 | +# https://leetcode.com/problems/find-words-that-can-be-formed-by-characters |
| 6 | + |
| 7 | +=begin |
| 8 | +You are given an array of strings words and a string chars. |
| 9 | +A string is good if it can be formed by characters from chars (each character can only be used once). |
| 10 | +Return the sum of lengths of all good strings in words. |
| 11 | +
|
| 12 | +Example 1: |
| 13 | +Input: words = ["cat","bt","hat","tree"], chars = "atach" |
| 14 | +Output: 6 |
| 15 | +Explanation: The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6. |
| 16 | +
|
| 17 | +Example 2: |
| 18 | +Input: words = ["hello","world","leetcode"], chars = "welldonehoneyr" |
| 19 | +Output: 10 |
| 20 | +Explanation: The strings that can be formed are "hello" and "world" so the answer is 5 + 5 = 10. |
| 21 | +
|
| 22 | +Constraints: |
| 23 | +1 <= words.length <= 1000 |
| 24 | +1 <= words[i].length, chars.length <= 100 |
| 25 | +words[i] and chars consist of lowercase English letters. |
| 26 | +=end |
| 27 | + |
| 28 | +# @param {String[]} words |
| 29 | +# @param {String} chars |
| 30 | +# @return {Integer} |
| 31 | +def count_characters(words, chars) |
| 32 | + char_hash = {} |
| 33 | + chars.each_char do |char| |
| 34 | + char_hash[char] ||= 0 |
| 35 | + char_hash[char] += 1 |
| 36 | + end |
| 37 | + |
| 38 | + answer = 0 |
| 39 | + words.each do |word| |
| 40 | + char_hash_clone = char_hash.clone |
| 41 | + |
| 42 | + has_all = true |
| 43 | + word.each_char do |c| |
| 44 | + if char_hash_clone[c] && (char_hash_clone[c] > 0) |
| 45 | + char_hash_clone[c] -= 1 |
| 46 | + else |
| 47 | + has_all = false |
| 48 | + break |
| 49 | + end |
| 50 | + end |
| 51 | + |
| 52 | + if has_all |
| 53 | + answer += word.size |
| 54 | + end |
| 55 | + end |
| 56 | + |
| 57 | + answer |
| 58 | +end |
| 59 | + |
| 60 | +# **************** # |
| 61 | +# TEST # |
| 62 | +# **************** # |
| 63 | + |
| 64 | +require "test/unit" |
| 65 | +class Test_count_characters < Test::Unit::TestCase |
| 66 | + def test_ |
| 67 | + assert_equal 6, count_characters(["cat","bt","hat","tree"], "atach") |
| 68 | + assert_equal 10, count_characters(["hello","world","leetcode"], "welldonehoneyr") |
| 69 | + end |
| 70 | +end |
0 commit comments