JS / JQuery的:string到文字分割脚本使用字典和最长的匹配?

给定一个string如:

var str = "thisisinsane"; 

由字典中的单词列表协助:

  var dic = [ "insane", "i", "is", "sin", "in", "this", "totally" ]; 

如何分裂成词?

对于这个string,有3个字来标识。 但是我们需要避免陷阱。 为了避免他们大部分时间,我知道我们可以攻击左边的句子,并试图find最长的单词是可能的。 发现后,我们可以攻击其余的string等

下面:input,可能的陷阱,右下angular的想要的输出。

  thisisinsane | | (this)isinsane / \ / \ (this,i)sinsane (this,is)insane / / \ / / \ (this,i,sin)ane (this,is,in)sane (this,is,insane) / <BEST IS> / <THIS ONE> (this,is,in,sane) 

最后,我们想要得到:

  var splited = ["this", "is", "insane"]; 

这是一个快速实现,将从左到右进行search,并匹配字典中最长的单词( jsfiddle )。 不过,我不确定自己实现这个是非常聪明的,因为它听起来像一个复杂的领域,甚至没有任何关于这个问题的知识,我可以说这个algorithm是有缺陷的开始。 如果有的话,你可能会更好地寻找现有的库。

不用说,这只是快速打字。 它没有以任何方式优化性能(它使用recursion,这实际上并不是必要的),也没有进行广泛的testing。 它适用于您的示例数据,但是在我testing的一些变体上。 如果我给出完整的代码示例,我希望将一些工作留给OP,所以如果要使用它,请随时改进。

 var splitByDictionary = function (input, dictionary) { "use strict"; // make sure we're going to look for longest-possible matches first dictionary.sort( function (a, b) { return b.length - a.length; } ); var foundWords = [], remaining = input; var result = (function match () { if( remaining.length === 0 ) { return true; } for( var i = 0; i < dictionary.length; i++ ) { if( remaining.substr( 0, dictionary[i].length ) === dictionary[i] ) { foundWords.push( dictionary[i] ); remaining = remaining.substr( dictionary[i].length ); return match(); } } return false; })(); return result ? foundWords : null; }; var splitted = splitByDictionary( "thisisinsane", ["insane", "i", "is", "sin", "in", "this", "totally"] ); console.log( splitted ); // ["this", "is", "insane"] 
Interesting Posts