๋ฐ˜๋ณต๋ฌธ์œผ๋กœ ๋ฌธ์ž์—ด ํƒ์ƒ‰, ๋น„๊ตํ•ด์„œ ๋ฌธ์ž์—ด๋กœ ๋ฆฌํ„ดํ•˜๋Š” ๋ฌธ์ œ์˜€๋‹ค.

 

1. ๋ฌธ์ œ

์•ŒํŒŒ๋ฒณ ๋Œ€๋ฌธ์ž๋กœ ์ด๋ฃจ์–ด์ง„ ๋ฌธ์ž์—ด์„ ์ž…๋ ฅ๋ฐ›์•„ ๊ฐ™์€ ๋ฌธ์ž๊ฐ€ ์—ฐ์†์œผ๋กœ ๋ฐ˜๋ณต๋˜๋Š” ๊ฒฝ์šฐ ๋ฐ˜๋ณต๋˜๋Š” ๋ฌธ์ž ๋ฐ”๋กœ ์˜ค๋ฅธ์ชฝ์— ๋ฐ˜๋ณต ํšŸ์ˆ˜๋ฅผ ํ‘œ๊ธฐํ•˜๋Š” ๋ฐฉ๋ฒ•์œผ๋กœ ๋ฌธ์ž์—ด์„ ์••์ถ•ํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค. ๋‹จ ๋ฐ˜๋ณตํšŸ์ˆ˜๊ฐ€ 1์ธ ๊ฒฝ์šฐ ์ƒ๋žตํ•ฉ๋‹ˆ๋‹ค.

 

์ž…๋ ฅ์˜ˆ์ œ | KKHSSSSSSSE

์ถœ๋ ฅ์˜ˆ์ œ | K2HS7E

 

2. ์ ‘๊ทผ๋ฐฉ๋ฒ•

๋ฐ˜๋ณต๋ฌธ์œผ๋กœ ๋ฌธ์ž์—ด ํƒ์ƒ‰ํ•ด์„œ ๋‘๊ฐœ์”ฉ ๋น„๊ตํ•ด์„œ countingํ•ด์ฃผ๊ณ  ์ˆซ์ž๋ฅผ ๋ฌธ์ž์—ด๋กœ ๋ฐ”๊พธ์–ด์„œ ๋„ฃ์–ด์ค€๋‹ค. 

 

 

3. ๋ฌธ์ œ ํ’€์ด 

1. ๊ฒฐ๊ณผ๋ฌผ์ด ๋ฌธ์ž์—ด์ด๋‹ค.

2. ๊ฐœ์ˆ˜๋ฅผ ์นด์šดํŒ…ํ•ด์„œ answer๋กœ ์ถœ๋ ฅํ•ด์•ผํ•œ๋‹ค.

3. -> ๋ฌธ์ž์—ด ๋‚ด ๋ฌธ์ž ๋‘๊ฐœ ๋น„๊ตํ•ด์„œ ๊ฐ™์œผ๋ฉด ์นด์šดํŒ… 

    -> ๋‹ค๋ฅธ ๊ฒฝ์šฐ answer์— ๋ฌธ์ž ๋ˆ„์ ํ•˜๊ณ 

    -> ๊ฐœ์ˆ˜๋„ ๋ฌธ์ž์—ด๋กœ ๋ฐ”๊ฟ”์„œ answer์— ๋ˆ„์ ํ•œ๋‹ค. (count > 1 ์ธ ๊ฒฝ์šฐ์—๋งŒ)

    -> ์นด์šดํŠธ๋Š” ์›๋ž˜๋Œ€๋กœ ์ดˆ๊ธฐํ™”ํ•ด์ค€๋‹ค. 

function solution(str){
	let answer = "";
    let count = 1;
    for(let i=0; i<str.length; i++){
    	if(str[i] === str[i+1]{
        	count++;
        } else {
        	answer += str[i];
            answer += count.toString();
            count = 1;
        }
    }
    return answer;
}

let str = "KKHSSSSSSSE";
console.log(solution(str));
    

๋ฐ˜๋ณตํšŸ์ˆ˜๊ฐ€ 1์ธ ๊ฒฝ์šฐ ์ƒ๋žตํ•˜๋Š” ์ฝ”๋“œ๋ฅผ ์ถ”๊ฐ€ํ•˜์ง€ ๋ชปํ–ˆ๋‹ค. 

 

 

ํ•ด๊ฒฐ๋ฐฉ๋ฒ•

else์•ˆ์— ๋˜ if๋ฌธ์„ ์ž‘์„ฑํ•  ์ˆ˜๊ฐ€ ์žˆ์—ˆ๋‹ค!
function solution(str){
	let answer = ""; //์ถœ๋ ฅ์ด ๋ฌธ์ž์—ด๋กœ ๋‚˜์™€์•ผํ•˜๋‹ˆ๊นŒ
    let count = 1; //์ œ์ผ ์•ž์— ๋ฌธ์žํ•˜๋‚˜๋Š” ๊ธฐ๋ณธ์œผ๋กœ ์žˆ์œผ๋‹ˆ๊นŒ 1๋กœ ์ €์žฅํ•ด์ฃผ๊ธฐ
    for(let i=0; i<str.length: i++){
    	if(str[i] === str[i+1]){
        	count++;
        } else {
        	answer += str[i]; // answer์— ๋ฌธ์ž๋ˆ„์ ํ•ด์ฃผ๊ณ 
            if(count>1) answer += count.toString();
            // count๊ฐ€ 1๋ณด๋‹ค ํฌ๋ฉด ๋ฌธ์ž๋กœ ๋ฐ”๊ฟ”์„œ answer์— ๋ˆ„์ 
            count = 1; // count๋Š” ๋‹ค์‹œ 1๋กœ ์ดˆ๊ธฐํ™”์‹œ์ผœ์ค€๋‹ค. 
          }
      }
      return answer;
}

let str = "KKHSSSSSSSE";
console.log(solution(str));

๋ฐ˜๋ณตํšŸ์ˆ˜๊ฐ€ 1์ธ๊ฒฝ์šฐ ์ƒ๋žตํ•˜๋ ค๋ฉด count ๊ฐ€ 1๋ณด๋‹ค ํฐ ๊ฒฝ์šฐ์—๋งŒ ์ถœ๋ ฅํ•˜๋„๋กํ•˜๋Š” ์ฝ”๋“œ๋ฅผ ์จ์ฃผ์—ˆ๋‹ค. 

 

 

 

3. ์‚ฌ์šฉํ•œ ๊ฐœ๋…

Number.toString()

์ˆซ์ž๋ฅผ ๋ฌธ์ž์—ด๋กœ ๋ฐ”๊ฟ”์ฃผ๊ธฐ

 

String(Number)

์ˆซ์ž๋ฅผ ๋ฌธ์ž์—ด๋กœ ๋ฐ”๊ฟ”์ฃผ๊ธฐ

+ Recent posts