JAVA 14ms naive solution, beat 95%


  • 0
    O

    My first version of solution was building this string backwards. However, it was slow. There are amazing solutions by others use only a couple of lines to finish the job too.
    To speed up, I changed to this new version. The idea is finding the length of the first section (or the only section where is no '-' needed). Then you add a '-' every K times adding a char.

    public String licenseKeyFormatting(String S, int K) {
        if (S == null) { return null; }
        int len = 0;
        for (char c : S.toCharArray()) {
            if (c != '-') { len++; }
        }
        StringBuilder sb = new StringBuilder();
        int n = len % K, i = 0, SLen = S.length();
        if (len <= K || n != 0) {
            if (n == 0) { n = len; }
            for (int j = 0; j < n; j++) {
                while (S.charAt(i) == '-') { i++; }
                sb.append(Character.toUpperCase(S.charAt(i++)));
            }
            if (len <= K) {
                return sb.toString();
            } else {
                sb.append('-');
            }
        }
        
        while (true) {
            for (int j = 0; j < K; j++) {
                while (i < SLen && S.charAt(i) == '-') { i++; }
                sb.append(Character.toUpperCase(S.charAt(i++)));
            }
            while (i < SLen && S.charAt(i) == '-') { i++; }
            if (i == SLen) {
                return sb.toString();
            }
            sb.append('-');
        }
    }

Log in to reply
 

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