您现在的位置是:首页 > 编程 > 数据结构和算法数据结构和算法
不规则字符串数组,组合成新的string数据
Tdou2020-05-20【数据结构和算法】人已围观
简介[a, s, d, 1, 2, 3, 5, 6, h6, 9, 12, 13, 14, 15, f, g]
这种数组,怎么组合成: a;s;d;1-3;5-6;h6; 9;12-15;f;g
解释:连续的正整数用横杠连接,不相的单独表示,这样可以节约数字占用的空间,12-15代表12至15,节省了13,14,如果是1-90呢,就大大节约了空间
JS 版本1

结果

最终使用JS版本
let test = ['a','s','d','1','2','3','5','6','9','12','13','14','15','f','g'],
gap = 1,
out = [],
compute = [],
lastNum = 1
test.forEach((item,index) =>{
+item >= 0 ? compute.push(item) : out.push(item)
if (compute.length > 1 ) {
if (compute[1] - compute[0] === gap && +test[index + 1] >= 0) {
gap++
lastNum = compute[1]
compute.length = 1
}else {
if (gap === 1){
out.push(compute[0])
compute = compute.slice(compute.length - 1)
}
else{
gap = 1
lastNum = +test[index + 1] >= 0 ? lastNum : compute[1]
out.push(compute[0] + '-' + lastNum)
compute = compute.slice(compute.length - 1)
}
}
}
})
console.log(out.join(';'))
友情链接
Tags:
很赞哦! ()
微信收款码
支付宝收款码