๐ฉ๐ปโ๐ป๋ฌธ์ ๋งํฌ
[์ธํ๋ฐ ์น์
5] ํ๊ธ ํ์ฅ (Javascript)
์ ๋ฃ ๊ฐ์์ธ ๊ด๊ณ๋ก ๋ฌธ์ ์ค๋ช
์ ์๋ตํฉ๋๋ค.
โ๏ธIdea Sketch
2021-06-25 ํ๋ก๊ทธ๋๋จธ์ค "์์ฃผํ์ง ๋ชปํ ์ ์"์ ๋ช ๋ต์ฒ๋ผ ํ๊ธฐ
1. let max = Number.MIN_SAFE_INTEGER; ์ฌ์ฉ
2. map, filter, forEach๋ ๋ฐฐ์ดo, ๋ฌธ์์ดx
str.forEach(v => {
console.log(v); // TypeError: str.forEach is not a function
})
3. split('')์ผ๋ก ๋ฌธ์์ด์ ๋ฐฐ์ด๋ก ์ ํํ๋ ๊ฒ๋ณด๋ค, for ๋ฐ๋ณต๋ฌธ์ ์ฐ๋ ๊ฒ ๋ ๋ซ๋ค๊ณ ํ๋จ
4. res[str[i]] = (res[str[i]] | 0) + 1; ์๋ฏธ
- || : OR ๋ ผ๋ฆฌ์ฐ์ฐ์
- res[str[i]] ๊ฐ์ด ์์ผ๋ฉด res[str[i]] + 1
- res[str[i]] ๊ฐ์ด ์์ผ๋ฉด 0 + 1
let res = [];
for (let i=0; i<str.length; i++) {
res[str[i]] = (res[str[i]] || 0) + 1;
}
5. ๋ฌธ์ ์ : res.length๊ฐ 0์ด๋ค.
- {} Object์ฒ๋ผ key:value ์์ผ๋ก ์ถ๋ ฅ๋์ง๋ง
- arr.length๊ฐ 0์ด๋ฉฐ,
- ๋ฐ๋ผ์ map(), filter(), forEach() ๋ฅผ ์ธ ์ ์๋ค.
function solution(str) {
let res = [];
let max = Number.MIN_SAFE_INTEGER;
for (let i=0; i<str.length; i++) {
res[str[i]] = (res[str[i]] || 0) + 1;
}
console.log(res.length, res) // output: 0 [ B: 3, A: 3, C: 5, D: 2, E: 2 ]
}
2021-06-25 Hash ๊ฐ์ฒด ์ฌ์ฉ
1. Hash ๊ฐ์ฒด ๊ฐ๋จํ ๋ฌธ๋ฒ
let hash = new Map();
hash.set('A', 1);
hash.get('A');
hash.has('A');
hash.delete('A');
hash.size;
for (let [key, val] of hash) {}
์ฃผ์
hash.size() (O)
hash.size (X)
ํท๊ฐ๋ฆด ๋ arr.length๋ฅผ ๋ ์ฌ๋ฆฌ์
2. (hash.get(x) || 0) + 1 ์๋ฏธ
- || : OR ๋ ผ๋ฆฌ์ฐ์ฐ์
- hash.get(x) ๊ฐ ์กด์ฌํ๋ฉด, hash.get(x) + 1
- hash.get(x) ๊ฐ ์กด์ฌํ์ง ์์ผ๋ฉด, 0 + 1
for (let x of str) {
hash.set(x, (hash.get(x) || 0) + 1);
}
3. val๊ฐ ๊ฐ์ฅ ํฐ key ์ฐพ๊ธฐ
for (let [key, val] of hash) {
if (val > max) [res, max] = [key, val]; // ๋ฐฉ๋ฒ 1.
[res, max] = (val > max) ? [key, val] : [res, max]; // ๋ฐฉ๋ฒ 2. ์ผํญ์ฐ์ฐ์
}
โ๏ธ์์ค์ฝ๋
2021-06-25 Hash ๊ฐ์ฒด ์ฌ์ฉ
function solution(str) {
let res = '';
let max = Number.MIN_SAFE_INTEGER;
let hash = new Map();
for (let x of str) {
hash.set(x, (hash.get(x) || 0) + 1);
}
for (let [key, val] of hash) {
if (val > max) [res, max] = [key, val];
}
return res;
}