我有一个字母数字字符串,我想检查其中的整数模式重复。而且它们应该是连续的。
Example
-
12341234qwe应该告诉我1234被重复。
-
1234qwe1234 should NOT告诉我1234重复,因为它不连续。
-
12121212应被视为12被重复,因为这是第一组被发现被重复的。但如果有一种算法可以找到1212正如之前重复设置的12然后我想它必须再次执行这些步骤1212.
我的想法是我可以通过迭代和比较来存储整数部分( <= '0' && >= '9')
在不同的StringBuilder
。然后我读到有关对字符串执行 FFT 的内容,它显示了重复的模式。但我不知道如何在 Java 中执行 FFT 并查找结果,而且我希望尝试在不进行信号处理的情况下执行此操作。我读过有关 KMP 模式匹配的内容,但它仅适用于给定的输入。还有其他方法可以做到这一点吗?
我认为你可以借助正则表达式来解决这个问题。考虑这样的代码:
String arr[] = {"12341234abc", "1234foo1234", "12121212", "111111111", "1a1212b123123c12341234d1234512345"};
String regex = "(\\d+?)\\1";
Pattern p = Pattern.compile(regex);
for (String elem : arr) {
boolean noMatchFound = true;
Matcher matcher = p.matcher(elem);
while (matcher.find()) {
noMatchFound = false;
System.out.println(elem + " got repeated: " + matcher.group(1));
}
if (noMatchFound) {
System.out.println(elem + " has no repeation");
}
}
OUTPUT:
abc12341234abc got repeated: 1234
1234foo1234 has no repeation
12121212 got repeated: 12
12121212 got repeated: 12
111111111 got repeated: 1
111111111 got repeated: 1
111111111 got repeated: 1
111111111 got repeated: 1
1a1212b123123c12341234d1234512345 got repeated: 12
1a1212b123123c12341234d1234512345 got repeated: 123
1a1212b123123c12341234d1234512345 got repeated: 1234
1a1212b123123c12341234d1234512345 got repeated: 12345
解释:
使用的正则表达式是(\\d+?)\\1
where
\\d - means a numerical digit
\\d+ - means 1 or more occurrences of a digit
\\d+? - means reluctant (non-greedy) match of 1 OR more digits
( and ) - to group the above regex into group # 1
\\1 - means back reference to group # 1
(\\d+?)\\1 - repeat the group # 1 immediately after group # 1
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)