【发布时间】:2017-10-22 15:59:04
【问题描述】:
我正在尝试寻找以下模式:
- 不止一次发生
- 长度超过 1 个字符
- 不是任何其他已知模式的子字符串
不知道可能发生的任何模式。
例如:
- 字符串“the boy fall by the bell”将返回
'ell', 'the b', 'y '。 - 字符串“男孩倒在铃旁,男孩倒在铃旁”将返回
'the boy fell by the bell'。
使用双 for 循环,它可能会被暴力强制非常效率低下:
ArrayList<String> patternsList = new ArrayList<>();
int length = string.length();
for (int i = 0; i < length; i++) {
int limit = (length - i) / 2;
for (int j = limit; j >= 1; j--) {
int candidateEndIndex = i + j;
String candidate = string.substring(i, candidateEndIndex);
if(candidate.length() <= 1) {
continue;
}
if (string.substring(candidateEndIndex).contains(candidate)) {
boolean notASubpattern = true;
for (String pattern : patternsList) {
if (pattern.contains(candidate)) {
notASubpattern = false;
break;
}
}
if (notASubpattern) {
patternsList.add(candidate);
}
}
}
}
但是,在搜索包含大量模式的大字符串时,这非常慢。
【问题讨论】:
-
某种意义上,这是一种压缩形式。您可能会对各种压缩算法进行一些研究。
-
为什么在您的第一个结果示例中单个空格不是元素?
-
@Björn 因为它只有一个字符长。
-
当然/me 擦眼镜
-
为什么“,”是一个带空格的逗号,不是您的第二个结果示例的一部分?