codingBat last2 using regex

Posted by polygenelubricants on Stack Overflow See other posts from Stack Overflow or by polygenelubricants
Published on 2010-04-12T06:18:22Z Indexed on 2010/04/12 6:23 UTC
Read the original article Hit count: 490

Filed under:
|
|

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.

© Stack Overflow or respective owner

Related posts about codingbat

Related posts about java