gpt4 book ai didi

java - 如何检查整数中的重复序列

转载 作者:IT老高 更新时间:2023-10-28 20:25:01 24 4
gpt4 key购买 nike

我有一个字母数字字符串,我想检查其中的模式重复是否只是整数。它们应该是连续的。

示例

  1. 12341234qwe 应该告诉我 1234 重复了。
  2. 1234qwe1234 应该 NOT 告诉我 1234 是重复的,因为它不连续。
  3. 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");
}
}

输出:

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

关于java - 如何检查整数中的重复序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10286677/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com