我的伙伴最近被问到这个面试问题,这让我很困惑!该问题要求他编写一个函数,如果字符串中有重复的子字符串且彼此相邻,该函数将返回 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
(\1
是 backreference 表示第 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/