์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ์•Œ๊ณ ๋ฆฌ์ฆ˜

[์ธํ”„๋Ÿฐ ์„น์…˜5] ํ•™๊ธ‰ ํšŒ์žฅ (Javascript)

์€์ง„ 2021. 6. 25. 16:23

์ธํ”„๋Ÿฐ

๐Ÿ‘ฉ๐Ÿปโ€๐Ÿ’ป๋ฌธ์ œ๋งํฌ

[์ธํ”„๋Ÿฐ ์„น์…˜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;
}