Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

394-字符串解码 #1

Open
YBFACC opened this issue May 28, 2020 · 0 comments
Open

394-字符串解码 #1

YBFACC opened this issue May 28, 2020 · 0 comments

Comments

@YBFACC
Copy link
Owner

YBFACC commented May 28, 2020

我的思路

  1. 找出没有【】嵌套的字段
  2. 使用string.replace()对目标字段进行替换
  3. 检测是否完成。是=>结束,否=>回到1

有点BFS味道

/**
 * @param {string} s
 * @return {string}
 */
var decodeString = function (s) {
  //得到数字和字符串
  let reg = /(\d+)\[([a-zA-Z]+)\]/g
  //检测是否完成
  let all = /\[.*\]/
  //循环直到完成编码
  while (all.test(s)) {
    s = s.replace(reg, (match, p1, p2) => p2.repeat(~~p1))
  }
  return s
}

作者:ybf20181212
链接:https://leetcode-cn.com/problems/decode-string/solution/jszheng-ze-by-ybf20181212/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

正则的可视化

QQ20200528-175054

正则工具

API详细可以查看MDN

栈思路

栈的思路参考自leetcode

其实也是套娃,层层计算

var decodeString = s => {
  let stack_num = []
  let stack_str = []
  let num = 0
  let res = ''
  for (const char of s) {
    if (!isNaN(char)) {
      num = num * 10 + ~~char
    } else if (char === '[') {
      stack_num.push(num)
      stack_str.push(res)
      res = ''
      num = 0
    } else if (char === ']') {
      res = stack_str.pop() + res.repeat(stack_num.pop())
    } else {
      res += char
    }
  }
  return res
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant