我有一个字母数字字符串,我想检查其中是否有整数重复的模式。而且它们应该是连续的。
例
我以为我可以通过迭代并将其与( <= '0' && >= '9')另一个整数进行比较来存储整数部分StringBuilder。然后,我读到有关在字符串上执行FFT的知识,它显示了重复的模式。但是我不知道如何在Java中执行FFT并寻找结果,我也希望尝试这样做而不去进行信号处理。我读到有关KMP模式匹配的信息,但这仅适用于给定的输入。还有其他方法吗?
( <= '0' && >= '9')
StringBuilder
您可以寻求正则表达式的帮助来解决此问题。考虑这样的代码:
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地方
(\\d+?)\\1
\\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