Yet another Java solution (15ms)


  • 0
    J
    public class Solution {
        public String licenseKeyFormatting(String S, int K) {
            if (S.length() == 0) return S;
            char[] chars = S.toCharArray();
            char[] res = new char[chars.length];
            int j = res.length;
            for (int i = chars.length - 1; i >= 0; i--) {
                char c = chars[i];
                if (Character.isAlphabetic(c)) res[--j] = Character.toUpperCase(c);
                else if (Character.isDigit(c)) res[--j] = c;
            }
            int len = res.length - j;
            int sp = len % K;
            int group = len / K;
            StringBuilder sb = new StringBuilder();
            sb.ensureCapacity(sp + group + len - sp);
            for (int i = 0; i < sp; i++) sb.append(res[j++]);
            for (int i = 0; i < group; i++) {
                if (i != 0 || sp > 0) sb.append('-');
                for (int rp = 0; rp < K; rp++) sb.append(res[j++]);
            }
            return sb.toString();
        }
    }
    

Log in to reply
 

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