๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm/์ธํ”„๋Ÿฐ(inflearn)

[ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ(JavaScript) ] 27 - ๊ฐ€์žฅ ์งง์€ ๋ฌธ์ž๊ฑฐ๋ฆฌ

by YWTechIT 2021. 8. 17.
728x90

๐Ÿ“ 27 - ๊ฐ€์žฅ ์งง์€ ๋ฌธ์ž๊ฑฐ๋ฆฌ

target์ด ๋ฌธ์ž์—ด s์—์„œ ๋–จ์–ด์ง„ ์ตœ์†Œ๊ฑฐ๋ฆฌ๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ๋ฌธ์ œ๋‹ค. ์—ฌ๊ธฐ์„œ ๊ณ ๋ คํ•ด์•ผํ•˜๋Š” ์ ์ด ์žˆ๋Š”๋ฐ, ์ฒ˜์Œ์— cnt = 0์œผ๋กœ ์ดˆ๊ธฐํ™”ํ•˜๊ณ  ๋ฌธ์ œ๋ฅผ ํ’€๊ณ ๋‚˜์„œ ๊ฐ•์˜๋ฅผ ๋“ค์–ด๋ณด๋‹ˆ๊นŒ ๋งจ ์ขŒ์ธก์„ ๊ธฐ์ค€์œผ๋กœ ํŒ๋‹จํ• ๋•Œ๋Š” ๋งจ ์ขŒ์ธก์— target์ด ์—†์œผ๋ฏ€๋กœ cnt๋ฅผ ์ œ์ผ ํฐ ์ˆซ์ž๋กœ ์ดˆ๊ธฐํ™”ํ•ด์•ผํ•œ๋‹ค๋Š” ๊ฒƒ์ด๋‹ค. ๊ทธ๋ ‡๊ฒŒํ•ด์•ผ reverse๋กœ ๊ฒ€์‚ฌํ• ๋•Œ๋„ ์˜ฌ๋ฐ”๋ฅธ ๋‹ต์„ ๋„์ถœํ•ด๋‚ผ ์ˆ˜ ์žˆ๋‹ค.

 

์ž˜ ์ดํ•ด๊ฐ€ ๋˜์ง€ ์•Š๋Š”๋‹ค๋ฉด ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค ์ž…๋ ฅ: tteachermodett ์ถœ๋ ฅ: 2 1 0 1 2 1 0 1 2 2 1 0 1 2์™€ ๊ฐ™์ด ๋‚˜์˜ค๋Š”์ง€ ํ™•์ธํ•ด๋ณด์ž.

 

let s = "teachermode";
let target = "e";

console.log(solution(s, target));

// ๋‚˜์˜์ฝ”๋“œ
function solution(s, target) {
  let n = s.length;
  let cnt = 1000;
  let answer = [];

  for (let i = 0; i < n; i++) {
    if (s[i] === target) cnt = 0;
    else cnt++;

    answer.push(cnt);
    console.log(answer);
  }

  cnt = 1000;

  for (let i = 0; i < n; i++) {
    if (s[n - i - 1] === target) cnt = 0;
    else cnt++;

    answer[n - i - 1] = Math.min(answer[n - i - 1], cnt);
  }

  return answer.join(" ");
}
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€