假设我有以下输入,我的实现语言是Java:
一个数组 A ,内容为:["brown fox", "jumped over the", "lazy dog", "dog", "the", "fish", "quantum burrito", "ox jumped over the laz", "and ate", "ate pie"]
字符串 S ,内容为:"the quick brown fox jumped over the lazy dog and ate pie"
(第一个字符索引0,最后一个字符索引55)
我需要(在典型的计算机上尽可能有效)组装字符串 S 的子字符串列表,这些子字符串(完全)包含在数组 A <的元素中/ em>,并按降序获取。我还需要知道每个匹配的字符串 S 中的起始和结束字符索引。 ......但有一些限制。
以下限制和特性适用于此问题:
只需查看字符串和数组即可手动执行此操作,在此示例中,解决方案如下,以正确的降序(从零开始索引)给出:
特别注意,&#34; ox跳过laz&#34;虽然它是 A 中 S 中最长的子串,但是<结果集中匹配强>不,因为它违反了&#34; fox&#34;和&#34;懒惰&#34;。
问题:我是否描述了一个可能存在于库中的相当标准的算法(部分或全部;我愿意用更简单的原始构建块来构建它)或者是这样的我需要从头开始实现自定义吗?
如果我从头开始实施,我认为我需要采取如下概括的方法:
["the quick brown fox jumped over the lazy dog and ate pie", "the quick brown fox jumped over the lazy dog and ate", "quick brown fox jumped over the lazy dog and ate pie", ... "the quick brown fox jumped", ... "brown fox jumped", ... "jumped", "quick", "brown", ... "pie"]
)。 听起来很慢......而且可能中等难以做好。
答案 0 :(得分:1)
您可以轻松地单独使用正则表达式。虽然以下是说明性的,并且不符合广泛的请求列表(即将结果放入数组并对其进行排序),但这些请求很容易实现。
“棘手”部分是字边界分隔符 \b
并使用群组 ()
来捕获您想要的实际群组想要匹配。
String[] A = {"brown fox", "jumped over the", "lazy dog", "dog", "the", "fish", "quantum burrito", "ox jumped over the laz", "and ate", "ate pie"};
String S = "the quick brown fox jumped over the lazy dog and ate pie";
for(String s : A) {
Pattern p = Pattern.compile(".*\\b(" +s+ ")\\b.*");
Matcher m = p.matcher(S);
while (m.find()) {
System.out.println(m.matches() + " => " + s);
System.out.println(" Start index: " + m.start(1));
System.out.println(" End index: " + m.end(1));
System.out.println(" Length: " + m.group(1).length());
}
}
上面匹配所有包含的字符串,只要它们是空格分隔的,并在主字符串中输出它们的开始/结束位置。