반응형

You are given an array of strings words and a string chars.

A string is good if it can be formed by characters from chars (each character can only be used once).

Return the sum of lengths of all good strings in words.

Example 1:

Input: words = ["cat","bt","hat","tree"], chars = "atach"
Output: 6
Explanation: The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6.

Example 2:

Input: words = ["hello","world","leetcode"], chars = "welldonehoneyr"
Output: 10
Explanation: The strings that can be formed are "hello" and "world" so the answer is 5 + 5 = 10.

난이도: easy

단어들의 모음인 words와 chars가 주어졌을 때,
word가 chars에 모두 포함되면 포함된 글자들의 길이를 모두 더한값을 구해라

이해가 안되서 몇번 다시 읽었다

단순하게 word의 글자들이 모두 포함되는지를 찾는 것이다

const pass = (word, chars) => {
  let count = 0;

  for (let i = 0; i < word.length; i++) {
    const char = word[i]
    if (chars.includes(char)) {
      chars = chars.replace(char, '')
      count++
    }
  }

  if (count === word.length) return true
  return false 
}

var countCharacters = function(words, chars) {
  let result = '';
  let length = 0;

  for (let i = 0; i < words.length; i++) {
    // 단어 체크 
    const word = words[i]
    if (pass(word, chars)) {
      length = length + word.length
    }
  }  
  return length  
};

처음에는 단순히 포함된 되면 되는줄 알고,
chars = chars.replace(char, '')이 코드 없이 포함되는지만 찾았고,
중복되는 경우도 생각해야 해서 추가한뒤 통과했다


반응형

+ Recent posts