
백준 9093번 단어뒤집기를 풀이했는데,
스택문제라서 직접 스택 클래스를 구현해보는 풀이로 접근했다.
class를 작성하는 과정에서 getter, setter에 관한 이론공부가 필요하여 따로 포스팅하였다.
_(underscore) 를 왜 작성하는지 모른다면 읽어보기!
https://velog.io/@awesome-hong/JS-Maximum-call-stack-size-exceeded-%ED%95%B4%EA%B2%B0-getter-setter-%EC%9D%B4%ED%95%B4%ED%95%98%EA%B8%B0
전체 코드는 다음과 같다.
// 파일 입력
const fs=require('fs');
const filePath=process.platform==='linux'?'/dev/stdin':'input.txt';
const input=fs.readFileSync(filePath).toString().split("\n");
// stack class 구현
class Stack{
constructor(){
this.data=[];
this.top=0;
}
push(element){
this.data[this.top]=element;
this.top+=1;
}
_top(){
if(!this.isEmpty()){
return this.data[this.top -1];
}
return -1;
}
pop(){
if(this.isEmpty()) return -1;
this.top-=1;
return this.data.splice(-1)[0];
}
isEmpty(){
if(!this.data.length) return true;
else return false;
}
}
// 문제 알고리즘
answer='';
const stack=new Stack();
const num=input[0];
for(let i=1;i<=num;i++){
input[i].split(" ").forEach(word => {
for(let i=0;i<word.length;i++){
stack.push(word.charAt(i));
}
for(let i=word.length;i>0;i--){
answer+=stack.pop();
}
answer+=" ";
});
console.log(answer);
answer='';
}
constructor()
stack 클래스에서 구현한 메소드는 push, top, pop, isEmpty이다.
이 문제에 필요한 메소드들만 구현하였다.
구현한 필드는 어레이를 할당할 data, 전체 사이즈를 저장할 number top이다.
push()
파라미터 하나를 받아 어레이 가장 끝에 저장하고, top을 1 증가시킨다.
top()
비어있다면 -1 반환,
비어있지않다면 가장 끝에 저장된 데이터를 반환.
pop()
비어있다면 -1 반환,
비어있지않다면 top을 미리 1 감소시키고, 가장 끝의 하나를 어레이 형태로 잘라내고, 그 내용물을 반환한다.
splice함수는 잘라낸 어레이을 반환하고, 기존 어레이는 잘라진 어레이로 업데이트한다.
isEmpty()
this.data의 길이가 0이면 비어있는 것이므로 true를 반환한다.
아니라면 false를 반환한다.
isEmpty()에서 this.data.length를 작성해야하는데,
냅다 this.length를 작성해서 계속 에러가 났었다. 휴.....
this.length는 스택 객체의 길이를 가져오라고 하는 의미인데,
문제는!
object의 길이는 반환값이 undefined이다.
if문의 인자로 if(!this.length) 이렇게 사용했기 때문에 false로 처리되어 런타입에러도 나지 않는다.ㅠㅠ
- tip: 객체의 길이는 keys함수로 구한다.
`Object.keys(stack).length` 와 같이 key값의 갯수로 판단된다.
확실히 하기 위해,
if(!this.data.length) 대신
if(this.data.length===0)으로 타입까지 확실히! 체크해주도록 하자!!
answer='';
const stack=new Stack();
const num=input[0];
for(let i=1;i<=num;i++){
input[i].split(" ").forEach(word => {
for(let i=0;i<word.length;i++){
stack.push(word.charAt(i));
}
for(let i=word.length;i>0;i--){
answer+=stack.pop();
}
answer+=" ";
});
console.log(answer);
answer='';
}
answer='' 에 이어붙이고 마지막에 한번에 출력하도록 한다.