all*_*tic 6 java string algorithm
假设我有以下输入,我的实现语言是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)
我需要(在典型的计算机上尽可能有效)组装一个包含(完全)在数组A的元素内的字符串S的子串列表,并按降序获取它们.我还需要知道每个匹配的字符串S中的起始和结束字符索引.......但有一些限制.
以下约束和特性适用于此问题:
通过查看字符串和数组手动完成此操作,在此示例中,解决方案将是以下正确的降序(基于零的索引)给出的:
注意,具体地说,"牛跃过LAZ",虽然它是最长的串一个是内小号,是不是因为它违反了"狐狸"和"懒惰"的字边界在结果集相匹配.
问题:我是否描述了一个可能存在于库中的相当标准的算法(部分或全部;我愿意用更简单的原始构建块构建它)或者这是一个如此定制的东西,我需要从头开始实现它?
如果我从头开始实现它,我想我需要采取一种广泛概述的方法,如下所示:
["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"]
听起来很慢......而且可能中等难以做到.
您可以仅依靠正则表达式轻松做到这一点。虽然以下内容是示范性的,并且不符合广泛的请求列表(即将结果放入数组中并对它们进行排序),但实现起来很简单。
“棘手”的部分是单词边界分隔符 \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());
}
}
Run Code Online (Sandbox Code Playgroud)
上面的内容匹配所有包含的字符串,只要它们是空格分隔的,并输出它们在主字符串中的开始/结束位置。
归档时间: |
|
查看次数: |
233 次 |
最近记录: |