码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 394. Decode String

时间:2019-12-24 10:17:52      阅读:84      评论:0      收藏:0      [点我收藏+]

标签:buffer   字符串   lse   return   split   start   spl   stack   ons   

将一个带格式的字符串转换成一个正常的字符串。仔细观察 ,是要用到字符串的repeat方法,中括号前的数字为重复次数,括号内的数据需要再次转译成正常字符串。

var numberMap = new Array(10).fill(0).reduce((obj, el, index) => {
      obj[index] = 1
      return obj
    }, {});
    function helper(arr, start) {
      var num = 1, firstInt = true, buffer = '', res = ''
      for (var i = start; i < arr.length; i++) {
        var c = arr[i];
        if (numberMap[c]) {
          c = c - 0;
          if (firstInt) {
            res += buffer;
            buffer = '';

            num = c
            firstInt = false
          } else {
            num = num * 10 + c;
          }
          continue
        }
        if (c === '[') {
          firstInt = true;
          buffer = '';
          var obj = helper(arr, i + 1);
          i = obj.index;
          res += obj.str.repeat(num);
          continue
        }
        if (c === ']') {
          return {
            str: res + buffer,
            index: i
          }
          continue
        }
        buffer += c
      }
      if (buffer.length) {
        res += buffer
      }
      return {
        str: res,
        index: i
      }
    }

    function decodeString(s) {
      var arr = s.split('');
      var obj = helper(arr, 0);
      console.log(obj)
      return obj.str
    }
    var str = decodeString('3[a]2[b4[F]c]');
    decodeString('3[a]2[bc]')
    decodeString('cccc')
    decodeString("3[a2[c]]")
    decodeString("2[abc]3[cd]ef")

另一个好妖的实现

function decodeString(s) {
    const stack = []
    let i = 0
    
    let curMulti = 0
    let curStr = []
    
    while (i < s.length) {
        const c = s[i]
        if (c >= '0' && c <= '9') {
            curMulti = (curMulti * 10) + (c - '0')
        } else if (c === '[') {
            stack.push(curMulti)
            stack.push(curStr)
            curMulti = 0
            curStr = []
        } else if (c === ']') {
            const lastStr = stack.pop()
            curMulti = stack.pop()
            for (let k = 0; k < curMulti; k++) {
                for (const cc of curStr) {
                    lastStr.push(cc)
                }
            }
            
            curMulti = 0
            curStr = lastStr
        } else {
            curStr.push(c)
        }
        i+=1
    }
    return curStr.join('')
}

leetcode 394. Decode String

标签:buffer   字符串   lse   return   split   start   spl   stack   ons   

原文地址:https://www.cnblogs.com/rubylouvre/p/12089271.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!