[LeetCode] 748. Shortest Completing Word

Chobby·2025년 5월 5일
1

LeetCode

목록 보기
401/427

😎풀이

  1. shortestCompletingWord: 가장 짧은 완성 문자열
  2. licenseFreq: onlyStrLicensePlate의 문자 빈도
  3. onlyStrLicensePlate: licensePlate에서 문자만 조회 후 소문자 변환하여 배열로 정의
  4. onlyStrLicensePlate 문자 순회
    4-1. 문자 빈도 확인
  5. words 순회
    5-1. 각 word 문자 빈도 확인
    5-2. licenseFreq의 문자 자격을 갖추었는지 판별
    5-3. 가장 짧은 완성형 문자인지 확인
  6. 탐색된 가장 짧은 완성형 문자 반환
function shortestCompletingWord(licensePlate: string, words: string[]): string {
    let shortestCompletingWord
    const licenseFreq = new Map<string, number>()
    const onlyStrLicensePlate = licensePlate.replaceAll(/[^a-zA-Z]/gi, '').toLowerCase().split('')
    for(const char of onlyStrLicensePlate) {
        licenseFreq.set(char, (licenseFreq.get(char) ?? 0) + 1)
    }
    for(const word of words) {
        const curWordFreq = new Map<string, number>()
        for(const char of word) {
            curWordFreq.set(char, (curWordFreq.get(char) ?? 0) + 1)
        }
        let isCompletingWord = true
        for(const [key, value] of licenseFreq) {
            if(curWordFreq.has(key) && curWordFreq.get(key) >= value) continue
            isCompletingWord = false
            break
        }
        if(!isCompletingWord) continue
        if(!shortestCompletingWord) {
            shortestCompletingWord = word
            continue
        }
        if(shortestCompletingWord.length > word.length) {
            shortestCompletingWord = word
            continue
        }
    }
    return shortestCompletingWord
};
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글