😎풀이

  1. words를 순회하며 모든 문자 분해
  2. 첫 단어 순회
    2-1. 모든 언어에 해당 문자열이 있는지 확인
    2-2. 해당 문자열 정답 배열에 추가
    2-3. 모든 단어로부터 해당 문자열 제거
  3. 공통된 문자열 반환
function commonChars(words: string[]): string[] {
    const result = []
    const hashMap = new Map<string, string[]>()
    for(const word of words) hashMap.set(word, [...word])
    const first = words[0]
    for(const char of first) {
        const isAllWordsIncluded = [...hashMap].every(([key, value]) => value.indexOf(char) >= 0)
        if(!isAllWordsIncluded) continue
        result.push(char)
        for(const [key, value] of hashMap) {
            const charIdx = value.indexOf(char)
            const filteredValue = value.toSpliced(charIdx, 1)
            hashMap.set(key, filteredValue)
        }
    }
    return result
};
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글