본문 바로가기

[Algorithm] 소문자로 이루어진 두 문자열에 중복된 문자가 존재하는지 확인하는 방법

by mugglim 2023. 1. 12.

두 문자열을 loop 돌거나, Set을 이용할 수도 있지만, bit masking을 통해 해결 가능!

Python

def wordToBits(word: str) -> int:
    bits = 0

    for ch in word:
        bit = ord(ch) - 97
        bits |= 1 << bit

    return bits

def hasAnyCommonLetter(s1: str, s2: str):
    return wordToBits(s1) & wordToBits(s2) > 0

TypeScript

const wordToBits = (word: string) => {
  return Array.from(word).reduce((bits, letter) => bits | (1 << (letter.charCodeAt(0) - 97)), 0);
};

const hasAnyCommonLetter = (s1: string, s2: string) => {
  return (wordToBits(s1) & wordToBits(s2)) > 0;
};

댓글