LeetCode 394. Decode String All In One

xgqfrms發表於2024-05-31

LeetCode 394. Decode String All In One

LeetCode 394. 解碼字串 演算法題解

errors

function decodeString(s: string): string {
  let stack = [];
  for(let i = 0; i < s.length; i ++) {
    // 巢狀 []
    let str = [];
    while(stack.length && s[i] === `]`) {
      let temp = stack.pop();
      if(temp !== `[`) {
        str.push(temp);
      } else {
        let n = stack.pop();
        str = [...str.join(``).repeat(n)];
      }
      stack.push(str.reverse().join(``));
    }
    stack.push(s[i]);
  }
  return stack.join(``);
};

/* 

Wrong Answer
23 / 34 testcases passed

Input
s =
"100[leetcode]"

Use Testcase


 */
 

image

solutions

function decodeString(s: string): string {
  const stack: string[] = [];
  for (let c of s) {
    stack.push(c);
    // 1. close square bracket
    if (stack[stack.length - 1] === `]`) {
      // remove `]`
      stack.pop();
      // collect strings
      const str: string[] = [];
      while (stack[stack.length - 1] !== `[`) {
        str.unshift(stack.pop());
      }
      // remove `[`
      stack.pop();
      // collect numbers
      const num: string[] = [];
      while (`0123456789`.includes(stack[stack.length - 1])) {
        num.unshift(stack.pop());
      }
      // repeat
      let temp = str.join(``).repeat(+num.join(``));
      stack.push(temp);
    }
  }
  return stack.join("");
};

image

function decodeString(s: string): string {
  const digits = '0123456789';
  const stack: [string, number][] = []
  let str = ''
  let multiplier = 0
  for (let c of s) {
    if (digits.includes(c)) {
      // fix: int number range [1, 300]. ✅
      // 10
      // 100
      multiplier = multiplier * 10 + parseInt(c)
      // ❌
      // multiplier = parseInt(c)
    } else if (c === '[') {
      stack.push([str, multiplier])
      // reset 
      str = ''
      multiplier = 0
    } else if (c === ']') {
      const [prevStr, prevMultiplier] = stack.pop()
      str = prevStr + str.repeat(prevMultiplier)
    } else {
      str += c
    }
  }
  return str
}

demos


https://leetcode.com/problems/decode-string/submissions/1272574909/?envType=study-plan-v2&envId=leetcode-75

(🐞 反爬蟲測試!打擊盜版⚠️)如果你看到這個資訊, 說明這是一篇剽竊的文章,請訪問 https://www.cnblogs.com/xgqfrms/ 檢視原創文章!

refs

https://leetcode.com/studyplan/leetcode-75/



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 釋出文章使用:只允許註冊使用者才可以訪問!

原創文章,版權所有©️xgqfrms, 禁止轉載 🈲️,侵權必究⚠️!


相關文章