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

[ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ(JavaScript) ] 28 - ๋ฌธ์ž์—ด ์••์ถ•

by YWTechIT 2021. 8. 17.
728x90

๐Ÿ“ 28 - ๋ฌธ์ž์—ด ์••์ถ•

if-else๋ฌธ์„ ์ด์šฉํ•ด์„œ ๊ตฌํ˜„ํ–ˆ๋‹ค.

let s = "KKHSSSSSSSE";

console.log(solution(s));

// ๋‚˜์˜์ฝ”๋“œ
function solution(s) {
  let cnt = 1;
  let answer = "";

  for (let x of s) {
    if (x === answer[answer.length - 1]) cnt++;
    else {
      if (cnt >= 2) answer += cnt;
      answer += x;
      cnt = 1;
    }
  }
  return answer;
}

// ๊ฐ•์‚ฌ๋‹˜ ์ฝ”๋“œ
function solution(s) {
  let cnt = 1;
  let answer = "";
  s += " ";

  for (let i=0; i<s.length-1; i++) {
    if (s[i] === s[i+1]) cnt++;
    else{
        answer += s[i];
        if(cnt>1) answer+=cnt
        cnt = 1
    }
}
  return answer;
}
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€