My buddy was recently asked this interview question and it has me stumped! The question asked him to write a function that would return true if a string had repeated substrings inside of it that were adjacent to each other.
For example, if given:
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
I was thinking that you could use some type of regular expression magic in Java, but that is as far as I could get. Any ideas?
Yes it is quite easy with regex. Simply try to find
regex like (.+)\\1
( \\1
is backreference representing match from group 1).
DEMO:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.