If you use regex, you only need one line:
String repeated = str.replaceAll("(.+?)\\1+", "$1");
Regular expression violation (.+?)\1:
(.+?) means "at least one character, but as little as possible, captured as group 1"\1 means "same character (s) as group 1
Here are some test codes:
String[] strs = {"AAAAAAAAA", "ABABAB", "ABCAB", "ABAb"};
for (String str : strs) {
String repeated = str.replaceAll("(.+?)\\1+", "$1");
System.out.println(repeated);
}
Conclusion:
A
AB
ABCAB
ABAb
source
share