두 문자열을 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;
};
댓글