๋ฐ์ํ
๋ฌธ์
๋ฌธ์์ด ๋ฆฌ์คํธ stringList์ ์ฟผ๋ฆฌ ๋ฆฌ์คํธ queryList๊ฐ ์์ ๋ ๊ฐ ์ฟผ๋ฆฌ ๋ฆฌ์คํธ์ ์๋ ๋ฌธ์์ผ์ด stringList์ ๋ฌธ์์ด ๋ฆฌ์คํธ์ ์๋์ง ์ฌ๋ถ๋ฅผ ํ์ธํด์ผ ํฉ๋๋ค. ๋ฌธ์์ด์ด ์์ผ๋ฉด true, ์์ผ๋ฉด false๊ฐ ๋ฉ๋๋ค. ๊ฐ ๋ฌธ์์ด์ ๋ํด์ ๋ฌธ์์ด์ ์กด์ฌ ์ฌ๋ถ๋ฅผ ๋ฆฌ์คํธ ํํ๋ก ๋ฐํํ๋ solution() ํจ์๋ฅผ ์์ฑํด์ฃผ์ธ์.
์ ์ฝ ์กฐ๊ฑด
- ์ ๋ ฅ ๋ฌธ์์ด์ ์์ด ์๋ฌธ์๋ก๋ง ์ด๋ฃจ์ด์ ธ ์์ต๋๋ค.
- ๋ฌธ์์ด์ ์ต๋ ๊ธธ์ด๋ 10^6์ ๋๋ค.
- ํด์ ์ถฉ๋์ ์์ต๋๋ค.
- ์๋์ ๊ฐ์ ๋ฌธ์์ด ํด์ฑ ๋ฐฉ๋ฒ์ ํ์ฉํด์ ํด์ฑ ํจ์๋ฅผ ๊ตฌํํ์ธ์.
- ๋ค์ ์์์ p๋ 31, m์ 1,000,000,007๋ก ํฉ๋๋ค.
- hash(s) = (s[0] + s[1]*p + ... s[n- 1]*p^n-1) mod m
์ ์ถ๋ ฅ์ ์
stringList | queryList | return |
["apple", "banana", "cherry"] | ["banana", "kiwi", " melon", "apple"] | [True, false, false, True] |
๋์ ํ์ด
- ์๊ฐ๋ณต์ก๋: O(N + M) (stringList: N, queryList: M)
function solution(stringList, queryList) {
const m = 1000000007;
const p = 31;
// ํด์ ํจ์
function hash(s) {
let hashValue = 0;
let p_pow = 1;
for (let i = 0; i < s.length; i++) {
hashValue = (hashValue + (s.charCodeAt(i) - 'a'.charCodeAt(0) + 1) * p_pow) % m;
p_pow = (p_pow * p) % m;
}
return hashValue;
}
// stringList์ ๋ชจ๋ ๋ฌธ์์ด์ ํด์ํ์ฌ ์ ์ฅ
const hashList = new Set();
for (const s of stringList) {
hashSet.add(hash(s));
}
// queryList์ ๊ฐ ๋ฌธ์์ด์ ๋ํด ๊ฒ์ฌ
const result = [];
for (const query of queryList) {
result.push(hashSet.has(hash(query)));
}
return result;
}
stringList์ ๋ชจ๋ ๋ฌธ์์ด์ ํด์ํ์ฌ ์ ์ฅํ ํ, queryList์ ๊ฐ ๋ฌธ์์ด์ ๋ํด ํด๋น ํด์๊ฐ ์กด์ฌํ๋์ง ํ์ธํฉ๋๋ค.
๋ค๋ฅธ ํ์ด
- ์๊ฐ๋ณต์ก๋: O(N + M) (stringList: N, queryList: M)
// โ polynomial hash๋ฅผ ๊ตฌํํ ๋ถ๋ถ
function polynomialHash(str) {
const p = 31; // ์์
const m = 1_000_000_007; // ๋ฒํท ํฌ๊ธฐ
let hashValue = 0;
for (let i = 0; i < str.length; i++) {
hashValue = (hashValue * p + str.charCodeAt(i)) % m;
}
return hashValue;
}
function solution(stringList, queryList) {
// โ stringList์ ๊ฐ ๋ฌธ์์ด์ ๋ํด ๋คํญ ํด์๊ฐ์ ๊ณ์ฐ
const hashList = stringList.map((str) => polynomialHash(str));
// โ queryList์ ๊ฐ ๋ฌธ์์ด์ด stringList์ ์๋์ง ํ์ธ
const result = [];
for (const query of queryList) {
const queryHash = polynomialHash(query);
if (hashList.includes(queryHash)) {
result.push(true);
} else {
result.push(false);
}
}
return result;
}
Reference
๋ฐ์ํ
'๐ข Algorithm' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Algorithm] ์ฌ๋ผ์ด๋ฉ ์๋์ฐ(Sliding Window) (1) | 2024.09.27 |
---|---|
[Javascript][Programmers] ์์ฃผํ์ง ๋ชปํ ์ ์ (0) | 2024.09.23 |
[Javascript] ๋ ๊ฐ์ ์๋ก ํน์ ๊ฐ ๋ง๋ค๊ธฐ (1) | 2024.09.10 |
[Javascript][Programmers] ๋ค๋ฆฌ๋ฅผ ์ง๋๋ ํธ๋ญ (0) | 2024.08.16 |
[Javascript][Programmers] ์นด๋ ๋ญ์น (0) | 2024.08.16 |