[리트코드] 394. Decode String | 스택

Urther·2021년 10월 21일
0

알고리즘

목록 보기
18/41
post-thumbnail

Problem | Decode String


Given an encoded string, return its decoded string.

The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.

You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.

Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4].

Input: s = "3[a]2[bc]"
Output: "aaabcbc"


✨ 접근 방식

괄호의 수를 반복해준다. 3[a] 라면 3번을 반복해주고, 2[bc]라면 bc를 2번 반복해주면 된다.

  1. 스택에 넣어서 ']'라는 문자열이 나올 때까지 push해준다.
  2. 스택에서 '['라는 문자열이 나올 때까지 pop해주어 문자열을 만들어준다.
    ( 만약, 위와 같은 예제라면 문자열 : cb => 스택이라 문자열이 반대로 나온다.)
  3. stack.pop() => '[' 문자열이 아직 스택에 남아있음
  4. 숫자가 나오는 만큼 빼준다.
    => 숫자 또한 200일지 10일지 모르기 때문에 while문을 돌려준다.
  5. 스택에 남아있는 글자를 모두 더해주고, reverse 해준다.

- ✔️ 전체 코드

/**
 * @param {string} s
 * @return {string}
 */
var decodeString = function(s) {
      let stack = [];
  // 문자열 붙이는 변수
  let answer="";
  for (let i = 0; i < s.length; i++) {
    let repeatCount = "";
    let tmp = "";
    if (stack.length != 0 && s[i] === "]") {
      while (stack[stack.length - 1] !== "[") {
        // 왼쪽 괄호가 나올 때까지 빼준다.
        tmp+=stack.pop();
      }
      // console.log('tmp',tmp);
      stack.pop();
      // 왼쪽 괄호 빼준다.
      while (!isNaN(stack[stack.length - 1])){
        repeatCount+=stack.pop();
      }
      repeatCount=parseInt(repeatCount.split('').reverse().join(''));
      stack.push(tmp.repeat(repeatCount));
      // console.log(stack);
      continue;
    }
    stack.push(s[i]);
  }
  while(stack.length!==0){
    answer+=stack.pop();
  }
  return answer.split('').reverse().join('');
};

- 🔥 필요한 기능들

문자열.split('').reverse().join('') : 문자열을 반대로 바꿔주는 기능
( 배열에서 자꾸 돌릴려고 했다. ㅠㅠ 배열에서 돌리려면 for문을 해줘야하는 번거로움이 발생하기 때문에 문자열은 문자열로 처리하려고 노력하기)

문자열.repeat(횟수) : 문자열을 횟수만큼 반복할 수 있다.

profile
이전해요 ☘️ https://mei-zy.tistory.com

0개의 댓글