482. License Key Formatting

这题是medium但是没什么思考难度,但是要注意很多corner case比如开头全是-----dash。
我的代码还是很长。

    public String licenseKeyFormatting(String S, int K) {
        S = S.toUpperCase();
        int i = S.length() - 1;
        String newS = "";
        int count = 0;
        while (i >= 0) {
            while (S.charAt(i) == '-') {
                //this should be while , not if. and the result could be -1.
                i--;
                if (i == -1) {
                    if (newS.startsWith("-")) {
                        newS = newS.substring(1, newS.length());
                    }
                    return newS;
                }
            }
            newS = S.charAt(i) + newS;
            count++;
            i--;

            if (count == K & i != -1) {
                newS = '-' + newS;
                count = 0;
            }
        }
        return newS;
    }

贴一个别人写的很优雅的:
http://www.ustopia.cn/t/43?cache=1496570644#Post202

public class Solution {
    public String licenseKeyFormatting(String S, int K) {
        int n = S.length();
        StringBuilder sb = new StringBuilder(n + n/K);
        for(int i = n-1, j = 0; i>-1; i--) {
            char c = S.charAt(i);
            if('-' == c) continue;
            if(c > 96) c -= 32;
            if((j++)%K == 0) sb.append('-');
            sb.append(c);
        }
        return sb.length() == 0? "": sb.deleteCharAt(0).reverse().toString();
    }
}

这篇是在东直门旁边的M记写的。。刚看完七幕人生的唐吉柯德。被BillBoard抓耳不想走了。

你可能感兴趣的:(482. License Key Formatting)