GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — 第 152 题:实现一个 normalize 函数,能将输入的特定的字符串转化为特定的结构化数据 · Issue #331 · Advanced-Frontend/Daily-Interview-Question

第 152 题:实现一个 normalize 函数,能将输入的特定的字符串转化为特定的结构化数据 #331

New issue
Copy link
New issue
Copy link
Open
Open
第 152 题:实现一个 normalize 函数,能将输入的特定的字符串转化为特定的结构化数据#331
Copy link
Labels
编程题阿里

Description

@gauseen
gauseen
opened on Dec 31, 2019
Issue body actions

字符串仅由小写字母和 [] 组成,且字符串不会包含多余的空格。
示例一: 'abc' --> {value: 'abc'}
示例二:'[abc[bcd[def]]]' --> {value: 'abc', children: {value: 'bcd', children: {value: 'def'}}}

Reacted by 梧桐, Guo Lizhi, gauseen and TomatoesMan

Activity

Next
  1. gauseen
    changed the title [-]实现一个 normalize 函数,能将输入的特定的字符串转化为特定的结构化数据[/-] [+]【阿里笔试】实现一个 normalize 函数,能将输入的特定的字符串转化为特定的结构化数据[/+] on Dec 31, 2019
  2. gauseen
    changed the title [-]【阿里笔试】实现一个 normalize 函数,能将输入的特定的字符串转化为特定的结构化数据[/-] [+]第 152 题:【阿里笔试】实现一个 normalize 函数,能将输入的特定的字符串转化为特定的结构化数据[/+] on Dec 31, 2019
  3. Nolaaaaa commented on Jan 2, 2020

    @Nolaaaaa
    Nolaaaaa
    on Jan 2, 2020
    More actions
    let normalize = str => {
      let result = {}
      let c
      
      // 字符串转化为数组
      let arr = str.split(/[\[\]]/g).filter(Boolean)
      
      // 生成结构化数据
      arr.forEach((item, index) => {
        if(index != 0) {
          c.children = {}
          c.children.value = item
          c= c.children
        } else {
          result.value = item
          c= result
        }
      })
      
      return result
    }
    let str = '[abc[bcd[def]]]'
    normalize(str)
    // {value: 'abc', children: {value: 'bcd', children: {value: 'def'}}}
    Reacted by 程序员依扬, 冯淼森, guyuezhai, 喜个阳阳, SelenaWong, Dylan, chenziyu and allenshu
  4. linbinhuang commented on Jan 2, 2020

    @linbinhuang
    linbinhuang
    on Jan 2, 2020
    More actions
    const normalize = (str) => {
      var result = {}
      str.split(/[\[\]]/g).filter(Boolean).reduce((obj, item, index, a) => {
        obj.value = item
        if(index !== a.length -1) {
          return (obj.children = {})
        }
      }, result)
      return result
    }
    Reacted by kaiseixd, LK26cc, 冯淼森, Angus, fariellany, leirensheng, guyuezhai, poppydani, Aaron, Allen and 15 more
    Reacted by ClubJ, snailboy and Borderick
    Reacted by Siebzehn and ff
  5. flyfox11 commented on Jan 6, 2020

    @flyfox11
    flyfox11
    on Jan 6, 2020
    More actions
    function normalize(str) {
    	let arr = str.match(/\w+/g)
    	let temp = {}
    	let obj
    	while(arr.length) {
    		let item = arr.pop()
    		temp.value = item
    		obj && (temp.children = obj)
    		if(arr.length) {
    			obj = {...temp}
    			temp = {}
    		}else {
    			obj = temp
    		}
    	}
    	return obj
    }
    Reacted by flyfox, interyang, larry0442, 冯淼森, lichenyang, fan, Chia June, cescxu0712, Hisenber, hardk-ngu and 1 more
    Reacted by flyfox and Chia June
  6. quanibm commented on Jan 7, 2020

    @quanibm
    quanibm
    on Jan 7, 2020
    More actions
    const normalize = str => {
      const arr = str.split(/[\[\]]/).filter(Boolean);
      const createArr = arr => {
        return arr.reduce((obj, val, n, arr) => {
          arr.length > 1 ? (obj.children = createArr(arr.slice(1))) : "";
          obj.value = arr[0];
          return obj;
        }, {});
      };
      return createArr(arr);
    };
    Reacted by 冯淼森
    Reacted by laoboxie and webwangshuai
  7. gauseen commented on Jan 7, 2020

    @gauseen
    gauseen
    on Jan 7, 2020
    Author
    More actions
    var normalize = (str) => {
      var list = str.match(/\w+/g)
      var obj = {}
      var curr = obj
      while (key = list.shift()) {
          curr.value = key
          if (list.length === 0) break
          curr.children = {}
          curr = curr.children
      }
      return obj
    }
    Reacted by 程序员依扬, Tako, yaocheng, Dylan and allenshu
  8. yygmind
    added
    阿里
    编程题
    on Jan 8, 2020
  9. yygmind
    changed the title [-]第 152 题:【阿里笔试】实现一个 normalize 函数,能将输入的特定的字符串转化为特定的结构化数据[/-] [+]第 152 题:实现一个 normalize 函数,能将输入的特定的字符串转化为特定的结构化数据[/+] on Jan 8, 2020
  10. yygmind commented on Jan 8, 2020

    @yygmind
    yygmind
    on Jan 8, 2020
    Contributor
    More actions

    字符串仅由小写字母和 [] 组成,且字符串不会包含多余的空格。
    示例一: 'abc' --> {value: 'abc'}
    示例二:'[abc[bcd[def]]]' --> {value: 'abc', children: {value: 'bcd', children: {value: 'def'}}}

  11. XiaoDHuang commented on Jan 14, 2020

    @XiaoDHuang
    XiaoDHuang
    on Jan 14, 2020
    More actions
    let normalize = (str) => {
        let arr = str.split(/[\[\]]/).filter(Boolean);
        let i = 0, obj = {}, cur = obj;
        while(i < arr.length) {
            if (i > 0) cur = cur.children = {};
            cur.value = arr[i];
            i ++;
        }
    
        return obj;
    }
    Reacted by youarebju, sujuan.liu and demo
  12. lhyt commented on Feb 2, 2020

    @lhyt
    lhyt
    on Feb 2, 2020
    More actions
    function normalize(str, res = {}) {
      if (str) {
        if (str[0] === "[") {
          const exec = /^\[(\w+)(\[.*\]){0,1}\]$/.exec(str);
          if (exec) {
            const [, value, next] = exec;
            res.value = value;
            next && normalize(next, (res.children = {}));
          }
        } else if (!/(\[|\])/.test(str)) {
          res.value = str;
        }
      }
      return res;
    }
    
    // 测试用例
    [
      "[a[b[c]]]",
      "",
      "asd",
      "[aads",
      "asdasd]",
      "[asddd]",
      "[a[d]",
      "[s[]]"
    ].reduce((acc, c) => ((acc[c] = normalize(c)), acc), {});

    es5、纯算法:

    function normalize(str) {
      if (!/(\[|\])/.test(str)) {
        return { value: str };
      }
      var len = str.length,
        quene = [],
        res = {},
        ret = res,
        current = "";
      for (var i = 0; i < len; i++) {
        var c = str[i];
        if (c === "[" || c === "]") {
          if (current) {
            quene.push(current);
            current = "";
          }
          if (c === "]") {
            var top = quene.shift();
            if (top) {
              res.value = top;
              if (quene.length) {
                res = res.children || (res.children = {});
              }
            }
          }
        } else {
          current += c;
        }
      }
      return ret;
    }
  13. kukuxi commented on Mar 1, 2020

    @kukuxi
    kukuxi
    on Mar 1, 2020
    More actions
    function normalize(str) {
      if (!str) return {};
      const arr = str
        .split(/[\[\]]/g)
        .filter(Boolean)
        .reverse();
      return arr.reduce((acc, cur) => {
        const temp = {};
        if (acc.value) { //说明此时acc !== {}
          temp.children = acc;
        }
        temp.value = cur;
        return temp;
      }, {});
    }
    
  14. jwdzzhz777 commented on Mar 12, 2020

    @jwdzzhz777
    jwdzzhz777
    on Mar 12, 2020
    More actions
    function normalize(str) {
      let current, result;
      while (current = str.match(/\[([a-z]+)\]/)) {
        let [res, value] = current;
        result = result ? { value, children: result } : { value };
        str = str.replace(res, '');
      }
      if (!result) result = {value: str};
      return result;
    }
    Reacted by dongmahesha
  15. 21 remaining items

  16. haipingzi commented on Apr 26, 2021

    @haipingzi
    haipingzi
    on Apr 26, 2021
    More actions
    function normalize(str) {
          let obj = {};
          const vals = str.split(/[\[\]]/g).filter(Boolean);
          for (let i = vals.length - 1; i >= 0; i--) {
            !obj.value ? obj.value = vals[i] : obj = {
              value: vals[i],
              children: {
                ...obj
              }
            }
          }
          return obj
        }
  17. zhelingwang commented on May 12, 2021

    @zhelingwang
    zhelingwang
    on May 12, 2021
    More actions

    用 reduce 搞定

    function normalize(input) {
      const arr = input.replace(/\[|\]/g, ',').split(',').filter(itm => itm);
      let result = {};
      arr.reduce((obj, cur, idx) => {
        const temp = {};
        temp.value = cur;
        if (obj.children) obj.children = temp;
        if (idx !== arr.length - 1) temp.children = {};
        if (idx === 0) result = temp;
        return temp;
      }, result);
      return result;
    }
    
    console.log(normalize('abc'));
    console.log(normalize('[abc[bcd[def]]]'));
  18. JYone223 commented on Aug 5, 2021

    @JYone223
    JYone223
    on Aug 5, 2021
    More actions

    用栈实现

    function normalize(str) {
      const stack = [];
      let res = {};
    
      for (let c of str) {
        if (c === ']') {
          let value = [];
          let top = stack.pop();
    
          while (top !== '[') {
            value.unshift(top);
            top = stack.pop();
          }
    
          if (res.value) {
            res.children = { ...res };
          }
          res.value = value.join('');
          continue;
        }
        stack.push(c);
      }
    
      if (stack.length) {
        res.value = stack.join('');
      }
    
      return res;
    }
  19. hcd1983 commented on Dec 13, 2021

    @hcd1983
    hcd1983
    on Dec 13, 2021
    More actions

    reverse 倒著回來

    function normalize(str) {
      const arr = str.replaceAll(']', '').split('[').filter(Boolean)
      const res = arr.reverse().reduce((obj, value, idx, a) => {
        if (idx > 0) {
          obj.children = {
            ...obj
          }
        }
        obj.value = value
        return obj
      }, {})
      return res
    }
    
    const str = '[abc[bcd[def]]]'
    console.log(normalize(str))
  20. miniflycn commented on Apr 16, 2022

    @miniflycn
    miniflycn
    on Apr 16, 2022
    More actions
    function parse(str) {
        let s = str
        const tokens = [
            /^\[/,
            /^\w+/,
            /^\]/
        ]
        let res = {}
        let point = undefined
        let parentMap = new Map()
        while (s) {
            for (let i = 0, l = tokens.length; i < l; i++) {
                let token = s.match(tokens[i])
                if (token) {
                    s = s.replace(tokens[i], '')
                    switch (i) {
                        case 0:
                            if (!point) {
                                point = res
                                parentMap.set(point, undefined)
                            } else {
                                point.children = {}
                                parentMap.set(point.children, point)
                                point = point.children
                            }
                            break
                        case 1:
                            point.value = token[0]
                            break
                        case 2:
                            point = parentMap.get(point)
                            break
                    }
                }
            }
        }
        return res
    }
  21. sundaydev-arch commented on Apr 19, 2022

    @sundaydev-arch
    sundaydev-arch
    on Apr 19, 2022
    More actions
    const normalize = (str = '') => {
        const result = {};
        const array = str.split(/[\[\]]/g).filter(Boolean);
        const { length } = array;
    
        array.reduce((previousValue, currentValue, currentIndex) => {
          previousValue.value = currentValue;
          if(currentIndex !== length - 1) return (previousValue.children = {})
        }, result);
        
        return result;
    }
    Reacted by Nathan Zhao and Dylan
    Reacted by Nathan Zhao
    Reacted by Nathan Zhao
    Reacted by Nathan Zhao
    Reacted by Nathan Zhao
    Reacted by Nathan Zhao
  22. Yxgm commented on May 31, 2022

    @Yxgm
    Yxgm
    on May 31, 2022
    More actions
    /**
     *
     * @param {string} str
     */
    const Normalize = (str) => {
      const obj = Object.create(null);
      const arr = str.match(/\w+/g); //[ 'abc', 'bcd', 'def' ]
      let index = 0;
    
      (function createObj(obj) {
        obj.value = arr[index++];
        if (index === arr.length) return;
        obj.children = {};
        return createObj(obj.children);
      })(obj);
    
      console.log(JSON.stringify(obj, undefined, '    '));
      return obj;
    };
    
    const Normalize = (str) => {
      const arr = str.match(/\w+/g); //[ 'abc', 'bcd', 'def' ]
      const obj = Object.create(null);
    
      arr.reduce((pre, current, index) => {
        pre['value'] = current;
        if (index == arr.length - 1) return null;
        pre['children'] = {};
        return pre['children'];
      }, obj);
    
      return obj;
    };
    
    console.log(Normalize('[abc[bcd[def]]]'));
  23. Yangfan2016 commented on Aug 28, 2022

    @Yangfan2016
    Yangfan2016
    on Aug 28, 2022
    More actions
    function normalize(str) {
        const list = str.split(/[\[\]]/).filter(Boolean); // ['abc','bcd','def']
        const res = {};
        let temp = {};
    
        for (let i = 0; i < list.length; i++) {
            const item = list[i];
            if (i === 0) {
                res.value = item;
                temp = res;
            } else {
                temp.children = {
                    value: item
                };
                temp = temp.children;
            }
        }
        return res;
    }
  24. CHENJIAMIAN commented on Sep 9, 2022

    @CHENJIAMIAN
    CHENJIAMIAN
    on Sep 9, 2022
    More actions
    let arr = '[abc[bcd[def[hij]]]]'.match(/\w+/g)
    //['abc', 'bcd', 'def']
    let obj = {};
    
    let res = {
        val: arr.pop()
    };
    while (arr.length > 0) {
        res = {
            val: arr.pop(),
            child: res
        };
    }
  25. mx369 commented on Sep 21, 2022

    @mx369
    mx369
    on Sep 21, 2022
    More actions
    const normalize = (v) => {
        if (v[0] != '[') return { value: v };
        const jsonStr = v.replace(/\[([^\[\]]+)/g, (_, value) => (`"value": "${value}","children":{`))
            .replaceAll(']', '}')
            .replace(',"children":{}', '');
        return JSON.parse(`{${jsonStr}}`);
    };
  26. mx369 commented on Sep 21, 2022

    @mx369
    mx369
    on Sep 21, 2022
    More actions
    const normalize = (str) => {
        const root = {};
        const holdMap = [];
        let hold = root;
        let floor = 0;
        let subVal = '';
        const setVal = () => {
            if (!subVal) return;
            hold.value = subVal;
            subVal = '';
        };
        for (var c of str) {
            if (c === '[') {
                setVal();
                holdMap[++floor] = hold;
                hold.children = {};
                hold = hold.children;
            } else if (c === ']') {
                setVal();
                hold = holdMap[--floor];
            } else {
                subVal += c;
            }
        }
        setVal();
        return root.value ? root : (root.children || {});
    };
  27. XW666 commented on Sep 22, 2023

    @XW666
    XW666
    on Sep 22, 2023
    More actions
     const normalize2 = (str) => {
        let arr = str.split(/[\[\]]/g).filter(Boolean)
        let len = arr.length - 1
        var result = {}
    //递归的形式
        let fun = (index, obj) => {
          for (let i = index; i < arr.length; i++) {
            obj.value = arr[index]
            if (i !== len) {
              obj.children = {}
              fun(index + 1, obj.children)
            }
          }
        }
        fun(0, result)
      }
    
  28. dixinL commented on Sep 27, 2023

    @dixinL
    dixinL
    on Sep 27, 2023
    More actions
    function normalize(str) {
      let temp = []
      let valStart = false
      let nowVal = ''
      let obj = {}
      let resKey = ''
      for (let i = 0; i < str.length; i++) {
        if (str[i] == '[') {
          valStart = true
          if (nowVal !== '') {
            obj[nowVal] = {value: nowVal}
            if (temp.length > 0) {
              if (!obj[temp[temp.length - 1]].children) {
                obj[temp[temp.length - 1]].children = []
              }
              obj[temp[temp.length - 1]].children.push(obj[nowVal])
            }
            temp.push(nowVal)
          }
          nowVal = ''
        } else if (str[i] == ']') {
          valStart = false
          if (nowVal !== '') {
            obj[nowVal] = {value: nowVal}
            if (temp.length > 0) {
              if (!obj[temp[temp.length - 1]].children) {
                obj[temp[temp.length - 1]].children = []
              }
              obj[temp[temp.length - 1]].children.push(obj[nowVal])
            }
            temp.push(nowVal)
          }
          if (temp.length == 1) {
            resKey = temp[0]
          }
          temp.pop()
          nowVal = ''
        } else if (valStart) {
          nowVal += str[i]
        }
      }
      return obj[resKey]
    }
    

    看起来大部分题解都只能支持逐级的链式结构,以数组方式处理字符串必然会丢失数据的结构化。这样处理数据导致重要参数丢失显然是不够健壮

    let str = '[abc[xx[yy][zz]][cc[dd]]]'
    console.log(str)
    console.log(normalize(str))
    

    可以以栈的方式存储上一级对象名称并根据对象的堆特性,来实现将字符串处理为简单对象的能力。

  29. keven-wang commented on Apr 2, 2024

    @keven-wang
    keven-wang
    on Apr 2, 2024
    More actions
    function nomalize(str) {
        const props = str.match(/\w+/g);
        if (props.length === 1) { 
            return { value: props[0] };
        }
        
        return props.reduceRight((children, parent) => {
            if (typeof children === 'string') {
                children = { value: children };
            }
            
            return { value: parent, children };
        });
    }
    console.log(JSON.stringify(nomalize('abc')));
    console.log(JSON.stringify(nomalize('[abc[bcd[def]]]')));
  30. yanxiaosong0902 commented on Jan 18, 2025

    @yanxiaosong0902
    yanxiaosong0902
    on Jan 18, 2025
    More actions
    function normalize(str: string) {
      if (str.indexOf('[') === -1) {
        return { value: str }
      }
      const reg = /^\[([a-z]+)(\[[a-z[\]]+\])*\]$/
    
      function parse(str: string) {
        const matcher = reg.exec(str)
        if (!matcher) {
          return { value: str }
        }
        if (matcher[1] && matcher[2]) {
          return { value: matcher[1], children: parse(matcher[2]) }
        }
        if (!matcher[2]) {
          return { value: matcher[1]}
        }
      }
    
      return parse(str)
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    编程题阿里

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      You are visitor 01402792 — GeezerVison does not store the pages you look up.
      Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.