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, '')
이 코드 없이 포함되는지만 찾았고,
중복되는 경우도 생각해야 해서 추가한뒤 통과했다
반응형
'Algorithm' 카테고리의 다른 글
[Leetcode] 442. Find All Duplicates in an Array (0) | 2022.03.07 |
---|---|
[Leetcode] 2144. Minimum Cost of Buying Candies With Discount (0) | 2022.03.07 |
[Leetcode] 605. Can Place Flowers (0) | 2022.03.05 |
[Leetcode] 155. Min Stack (0) | 2022.03.05 |
[Leetcode] 1306. Jump Game III (0) | 2022.03.04 |