[英]Adjacent Repeated Substrings of Arbitrary Length
最近,我的好友被問到了這個面試問題,這讓我感到困惑! 這個問題要求他編寫一個函數,如果一個字符串中有重復的子字符串彼此相鄰,則該函數將返回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中使用某種類型的正則表達式魔術,但這是我所能做到的。 有任何想法嗎?
是的,使用正則表達式非常容易。 只需嘗試find
像(.+)\\1
這樣的正則表達式
( \\1
是反向引用,表示來自組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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.