java - 任意长度的相邻重复子串

标签 java regex string algorithm

我的伙伴最近被问到这个面试问题,这让我很困惑!该问题要求他编写一个函数,如果字符串中有重复的子字符串且彼此相邻,该函数将返回 true。

例如,如果给定:

 String first = "ABCxyABC"; //This string would return false because both "ABC" are not next to each other

 String second = "ABCzzCDE"; //This string would return true because both "z" are next to each other

 String third = "12341234zAE"; // This string returns true as well, as "1234" is repeated and back-to-back

我认为您可以在 Java 中使用某种类型的正则表达式魔术,但这是我所能得到的。有什么想法吗?

最佳答案

是的,使用正则表达式很容易。只需尝试查找 正则表达式,如 (.+)\1
(\1backreference 表示第 1 组的匹配项)。

演示:

String first  = "ABCxyABC"; 
String second = "ABCzzCDE"; 
String third  = "12341234zAE";

Pattern p = Pattern.compile("(.+)\\1");

System.out.println(p.matcher(first).find());  //false
System.out.println(p.matcher(second).find()); //true
System.out.println(p.matcher(third).find());  //true

关于java - 任意长度的相邻重复子串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33714670/

相关文章:

regex - 匹配以 '/' 开头的字符的所有实例

c# - 使用 regex.replace() 在指定字符数后添加空格的正确语法是什么?

java - 从 Java 中的字符串中获取子字符串

java - 我将如何将 boolean 字符串更改为 JTable 中的 JCheckBox?

java - 如何针对不同的数据类型使用MapStruct?

javascript - 替换换行符

java - 从 Java 中的字符串中删除尾部斜杠

java - 电影海报未通过 TheMovieDB 显示

java - 我们如何在java中使用Akka-remote-access进行2路通信

javascript - 使用动态 RegExp 获取 $1 捕获组