对于学校项目,目标是将查询字符串与 Song 对象内的歌词字符串进行模糊匹配。整个数据结构是一个由唯一单词与歌词中包含该单词的歌曲集配对的 TreeMap。
我有包含查询字符串的初步匹配歌曲集。这里的转折是我必须根据匹配部分中的字符数为每首结果歌曲分配一个排名,包括空格。例如,搜索“她爱你”会在匹配项中返回以下内容:
“......她爱你......”披头士乐队,排名 = 13
“......她只是爱你......”邦妮雷特,排名 = 18
“......她爱我,你......”猫王普雷斯利,排名=23
我用来对结果进行排序的是:
for (int i=0; i<lyrics.length; i++) {
if (lyrics[i].equals(query[0])) { //got the start point
start=i; //adjust the start index point
//loop through lyrics from start point
for (int j=1; j<query.length; j++) {
if (lyrics[j].equals(query[query.length-1])) {
end=i; //found the last word
}
//if next lyric word doesn't match this query word
if (!lyrics[i+j].equals(query[j])) {
//advance loop through lyrics. when a match is found, i is adjusted to
//the match index
for (int k= i+j+1; k<lyrics.length; k++) {
if (lyrics[k].equals(query[j]) || lyrics[k].equals(query[0]))
i=k++;
} //end inner advance loop
} //end query string test
}//end query test loop
song.setRanks(start, end); //start and end points for the rank algorithm.
} //end start point test
由于结果集中的所有歌曲都以任何特定顺序包含查询词,因此它们不会全部包含在结果打印输出中。使用此算法,如果查询不匹配任何特定长度,我如何设置触发器以从集合中删除歌曲?
编辑-Lucene 是解决这个问题的方法吗?这是项目中的一个灰色地带,明天我将在课堂上提出。他允许我们为这个项目选择任何数据结构,但我不知道使用另一个实现进行字符串匹配是否会通过集合。
编辑 2 @belisarius-我看不到编辑距离如何应用在这里。Levenshtein 距离最常见的应用需要一个长度为 n 的字符串 a 和长度为 m 的字符串 b,而距离是 a==b 所需的编辑次数。对于这个项目,只需要匹配中字符的排名,起点和终点是未知的。通过对上面发布的代码进行一些更改,我可以准确地找到起点和终点。如果歌词以任何方式不适合搜索,我需要一种从集合中删除不匹配项的方法。