GeezerVison is showing github.com — 第 152 题:实现一个 normalize 函数,能将输入的特定的字符串转化为特定的结构化数据 · Issue #331 · Advanced-Frontend/Daily-Interview-Question
第 152 题:实现一个 normalize 函数,能将输入的特定的字符串转化为特定的结构化数据 #331Description字符串仅由小写字母和 [] 组成,且字符串不会包含多余的空格。
示例一: 'abc' --> {value: 'abc'}
示例二:'[abc[bcd[def]]]' --> {value: 'abc', children: {value: 'bcd', children: {value: 'def'}}} Reacted by 梧桐, Guo Lizhi, gauseen and TomatoesMan Activitychanged the title [-]实现一个 normalize 函数,能将输入的特定的字符串转化为特定的结构化数据[/-] [+]【阿里笔试】实现一个 normalize 函数,能将输入的特定的字符串转化为特定的结构化数据[/+] on Dec 31, 2019changed the title [-]【阿里笔试】实现一个 normalize 函数,能将输入的特定的字符串转化为特定的结构化数据[/-] [+]第 152 题:【阿里笔试】实现一个 normalize 函数,能将输入的特定的字符串转化为特定的结构化数据[/+] on Dec 31, 2019Nolaaaaa commented on Jan 2, 2020 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 linbinhuang commented on Jan 2, 2020 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 flyfox11 commented on Jan 6, 2020 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 quanibm commented on Jan 7, 2020 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 gauseen commented on Jan 7, 2020 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 changed the title [-]第 152 题:【阿里笔试】实现一个 normalize 函数,能将输入的特定的字符串转化为特定的结构化数据[/-] [+]第 152 题:实现一个 normalize 函数,能将输入的特定的字符串转化为特定的结构化数据[/+] on Jan 8, 2020yygmind commented on Jan 8, 2020 字符串仅由小写字母和 [] 组成,且字符串不会包含多余的空格。
示例一: 'abc' --> {value: 'abc'}
示例二:'[abc[bcd[def]]]' --> {value: 'abc', children: {value: 'bcd', children: {value: 'def'}}} XiaoDHuang commented on Jan 14, 2020 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 lhyt commented on Feb 2, 2020 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;
}kukuxi commented on Mar 1, 2020 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;
}, {});
}
jwdzzhz777 commented on Mar 12, 2020 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;
}haipingzi commented on Apr 26, 2021 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
}zhelingwang commented on May 12, 2021 用 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]]]'));JYone223 commented on Aug 5, 2021 用栈实现
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;
}hcd1983 commented on Dec 13, 2021 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))miniflycn commented on Apr 16, 2022 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
}sundaydev-arch commented on Apr 19, 2022 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 Yxgm commented on May 31, 2022 /**
*
* @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]]]'));Yangfan2016 commented on Aug 28, 2022 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;
}CHENJIAMIAN commented on Sep 9, 2022 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
};
}mx369 commented on Sep 21, 2022 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}}`);
};mx369 commented on Sep 21, 2022 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 || {});
};XW666 commented on Sep 22, 2023 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)
}
dixinL commented on Sep 27, 2023 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))
可以以栈的方式存储上一级对象名称并根据对象的堆特性,来实现将字符串处理为简单对象的能力。 keven-wang commented on Apr 2, 2024 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]]]')));yanxiaosong0902 commented on Jan 18, 2025 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)
}
MetadataMetadataDevelopmentNo branches or pull requestsIssue actions
|