[LeetCode] Goal Parser Interpretation

HyeLin·2022년 6월 24일
0
post-thumbnail

문제

You own a Goal Parser that can interpret a string command. The command consists of an alphabet of "G", "()" and/or "(al)" in some order. The Goal Parser will interpret "G" as the string "G", "()" as the string "o", and "(al)" as the string "al". The interpreted strings are then concatenated in the original order. Given the string command, return the Goal Parser's interpretation of command.

문제 해석

  • 괄호가 비어있으면 'o'로 출력, (al)이면 괄호 제외하고 'al'출력
  • G는 그냥 출력!

코드

var interpret = function(command) {
 let arr=[]
 
 for(let i=0; i<command.length;){
   if(command[i]==='G'){
     arr.push('G')
     i ++
   }else if(command[i+1] === ')'){
     arr.push('o')
     i +=2
   }else{
     arr.push('al')
     i +=4
   }
 }
  
  return arr.join('')
};

interpret("(al)G(al)()()G")

배운 것!

for문의 증감식을 생략하지 않고

for(let i=0; i<command.length; i++)

로 했었는데,.. 계속 답이 안나와서 고민했다.
하지만, for 반복문 블록 내에 증감식 문장을 포함하면 for 반복문 자체에 증감식 생략 가능 이라는 것!!! ✨

당연하지
난 각 조건에 따라 i 값을 증가시켰으니까.. 습관적으로 for문 안에 증감식을 쓰다보니까
알아차리기까지 시간이 걸렸다.

for문의 초기화식, 조건식, 증감식은 모두 생략 가능하다.
초기화식 -> for문 이전에 먼저 선언했으면 생략 가능
조건식 -> 무한 반복하겠다는 의미, 특정 조건을 만족하면 빠져나올 수 있도록 break문을 써줘야함

But ❗️ 소괄호 안에 세미콜론은 생략이 불가능하다

  for( ; num < 5; num++)
  for( ; num < count; ) 

당연하게 생각했던 것들을 다시 한번 들여다본 경험이라서 좋았다!

profile
개발자

0개의 댓글