문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음
문자열 배열 words와 문자열 chars가 주어진다.
문자열이 chars의 문자로 구성된다면 좋다(각 문자는 words에 있는 각 단어에 대해 오직 한번만 사용할 수 있다).
words에서 좋은 단어 모두의 길이 합을 반환해라.
#1
Input: words = ["cat", "bt", "hat", "tree"], chars = "atach"
Output: 6
Explanation: 만들 수 있는 문자열은 "cat"과 "hat"이라서 답은 3 + 3 = 6이다.
#2
Input: words = ["hello", "world", "leetcode"], chars = "welldonehoneyr"
Output: 10
Explanation: 만들 수 있는 문자열은 "hello"와 "world"라서 답은 5 + 5 = 10이다.
class Solution {
public int countCharacters(String[] words, String chars) {
Map<Character, Integer> charMap = new HashMap<>();
for(char c : chars.toCharArray()){
charMap.put(c, 1 + charMap.getOrDefault(c, 0));
}
int result = 0;
for(String word : words){
Map<Character, Integer> copyMap = new HashMap<>(charMap);
for(char c : word.toCharArray()){
if(copyMap.containsKey(c) && copyMap.get(c) != 0){
copyMap.put(c, copyMap.get(c) - 1);
}else{
result -= word.length();
break;
}
}
result += word.length();
}
return result;
}
}