任意长度的相邻重复子串

时间:2015-11-14 23:38:08

标签: 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 个答案:

答案 0 :(得分:2)

是的,正则表达式很容易。只需尝试像find一样(.+)\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