Java easy to understand solution

  • 4
    public String licenseKeyFormatting(String S, int K) {
        S = S.replaceAll("[-]", "");
        S = S.toUpperCase();
        StringBuilder sb = new StringBuilder();
        int i=sb.length()-K;
        while(i>0) {
            sb.insert(i, '-');
            i = i-K;
        return sb.toString();

  • 0


    The first 2 lines can merge -

       S = S.replaceAll("[-]", "").toUpperCase();

    Line 3 and 4 can merge -

       StringBuilder sb = new StringBuilder(S);

    Actually, the above 2 lines can further merge into 1.
    But, let's not sacrifice readability.

  • 0

    @zzhai correct. Submitted the solution with merged lines. Uploaded this to increase readability. Din't realize the 2nd merge though. Thanks for pointing it out.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.