새소식

Baekjoon

[BaekJoon] 4889 번 안정적인 문자열 문제 - (nodejs)

  • -
728x90
문제 번호 :  4889번

문제 바로가기 https://www.acmicpc.net/problem/4889

 

<<< 문제 내용 >>>



 

const fs = require('fs'); const filePath = process.platform === 'linux' ? '/dev/stdin' : './input.txt'; let input = fs.readFileSync(filePath).toString().trim().split('\n'); for(let i in input){ let temp = input[i].split(''); let arr = []; let cnt = 0; if(temp[0] === '-') break; for(let j in temp){ if(temp[j] === '{'){ arr.push(temp[j]); } else{ if(arr[arr.length-1] === '{'){ arr.pop(temp[j]); } else{ arr.push(temp[j]); } } } while(arr.length){ let index = arr.pop(); if(index === arr[arr.length-1]){ arr.pop(); cnt += 1; }else{ arr.pop(); cnt += 2; } } console.log(Number(i)+1+'. '+cnt); }

[1번째 풀이]

스택에 우선 { 와 }를 담습니다. 담을 때 }면 바로 앞에 {가 있는지 확인 후 있다면 pop으로 둘다 담지 않습니다.

우선적으로 처리 후

스택이 빌때까지 마지막 2개씩 비교하면서 만약 두개의 모양이 같으면 1개만, 다르면 2개씩 바꾸면서 처리합니다.

(문제가 짝수이기 때문에 가능)

 

const fs = require('fs'); const filePath = process.platform === 'linux' ? '/dev/stdin' : './input.txt'; let input = fs.readFileSync(filePath).toString().trim().split('\n'); for(let i in input){ let temp = input[i].split(''); let arr = []; let cnt = 0; if(temp[0] === '-') break; for(let j in temp){ if(temp[j] === '{') arr.push(temp[j]); else{ if(!arr.length){ arr.push('{'); cnt++; }else{ arr.pop(); } } } console.log((Number(i)+1)+'. '+(cnt + arr.length/2)); }

 

[2번째 풀이]

다른 사람의 정답을 보니, 스택이 비었을때 }가 오면 {로 변경하고 변경횟수를 더하고,

스택이 있을때 }가 오면 비워줍니다.

반복문이 끝나고도 남아있는 arr의 개수( '{' 만 남아있음 )와 cnt의 개수를 이용하여서 출력합니다.

 

이 방법이 조금 더 깔끔하고 좋네요.

 

 

 

도움이 되셨다면 공감 부탁드립니다.

Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.