这就是问题所在假设我有这些弦:
苹果iPad mini 32GB
苹果iPad mini 64GB
苹果ipad air 64gb
苹果ipad air 32gb
松下gh4
三星s2 galaxy
三星S2银河红
三星S3 Galaxy
我希望这些字符串按如下方式分组:
苹果iPad mini:[苹果iPad mini 32GB,苹果iPad mini 64GB]
苹果ipad air:[苹果ipad air 64gb,苹果ipad 32gb]
松下gh4:【松下gh4】
三星S2 Galaxy:[三星S2 Galaxy,三星S2 Galaxy Red]
三星S3 Galaxy
重点是将项目的名称与其属性(颜色、内存容量等)分开。
我用这个算法寻找最长的公共子串:
link
你们能分享一下你们的想法吗不需要代码或实现。谢谢您。
编辑:
this.data = _.sortBy(this.data, function(item) {
return item.title;
});
var i = 0;
var groups = {};
var len = this.data.length - 1;
while(i < len) {
var key = this.lcs(this.data[i][this.attr], this.data[i+1][this.attr]) || this.data[i][this.attr];
groups[key] = true;
i++;
while(this.data[i][this.attr].startsWith(key) && i < len) {
i++;
}
}
console.log(groups)
这很好(只测试了添加键)。但我想把三星S3 Galaxy也列入名单。谢谢你们的帮助!
最佳答案
如果你只想简单地按最长的公共前缀分组(这意味着即使“apple ipad”会产生一个更大的组,也会选择“apple ipad mini”),那么也许是这样的?
sort the list
i = 0
while i < end of list:
key = longest common prefix of list[i] & list[i + 1]
or list[i] if the common prefix is less than (1?) words or i is the last index
groups[key] = list[i++]
while key is prefix of list[i]:
add list[i++] to groups[key]
关于javascript - 按最长的公共(public)起始子字符串分组字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34210034/