codingBat plusOut using regex

前端 未结 4 1077
离开以前
离开以前 2020-12-12 01:20

This is similar to my previous efforts (wordEnds and repeatEnd): as a mental exercise, I want to solve this toy problem using regex only.

Description from codingbat.

4条回答
  •  长情又很酷
    2020-12-12 01:55

    An extremely simple solution, using \G:

    word = java.util.regex.Pattern.quote(word);
    return str.replaceAll("\\G((?:" + word + ")*+).", "$1+");
    

    However, there is a caveat. Calling plusOut("12xxxxx34", "xxx") with the implementation above will return ++xxx++++.

    Anyway, the problem is not clear about the behavior in such case to begin with. There is even no test case for such situation (since my program passed all test cases).

    The regex is basically the same as the looping solution (which also passes all test cases):

    StringBuilder out = new StringBuilder(str);
    
    for (int i = 0; i < out.length(); ) {
        if (!str.startsWith(word, i))
            out.setCharAt(i++, '+');
        else
            i += word.length();
    }
    
    return out.toString();
    

    Repeatedly skips the word, then replace the current character if it is not prefix of word.

提交回复
热议问题