codingBat last2 using regex
- by polygenelubricants
Okay guys, this is similar to my repeatEnd and wordEnds efforts; I want to solve this codingBat Warmup-2 question using only regex-based techniques as a "brain gymnastics" exercise.
This solution works for codingBat tests:
public int last2(String str) {
return str.isEmpty() ? 0
: str.split(
str.replaceAll(
".*(.)(.)",
"$1(?=$2)" //.replaceAll("(\\$.)", "\\\\\\\\Q$1\\\\\\\\E")
),
-1
).length - 1 - 1;
}
The monstrous octo-slashes aren't needed to pass codingBat, but is needed for a proper regex-based solution. That is, if I want this (and I do!):
assert last2("..+++...++") == 2;
I'd have to uncomment the second .replaceAll. I'm just wondering if others can come up with a simpler, more elegant regex solution for this problem.
Preferably one that doesn't contain octo-slashes.