[LeetCode] Find Words That Can Be Formed by Characters

아르당·5일 전

LeetCode

목록 보기
245/254
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

문자열 배열 words와 문자열 chars가 주어진다.
문자열이 chars의 문자로 구성된다면 좋다(각 문자는 words에 있는 각 단어에 대해 오직 한번만 사용할 수 있다).
words에서 좋은 단어 모두의 길이 합을 반환해라.

Example

#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이다.

Constraints

  • 1 <= words.length <= 1000
  • 1 <= words[i].length, chars.length <= 100
  • words[i]와 chars은 영어 소문자로 구성된다.

Solved

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;
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글