My Java code beats 99.67%


  • 1
    A
    public String licenseKeyFormatting(String S, int K) {
        StringBuilder sb = new StringBuilder();
        char[] a = S.toCharArray();
        int dashes = 0;
        for (int i = 0; i < a.length; i++) {
            if (a[i] == '-') {
                dashes++;
            }
            else {
                if (a[i] >= 'a' && a[i] <= 'z') {
                    a[i] = (char)('A' + (a[i] - 'a'));
                }
            }
        }
        
        int remain = (a.length - dashes) % K;
        int i = 0;
        for (char c : a) {
            if (c == '-') {
                continue;
            }
            if (remain > 0) {
                sb.append(c);
                remain--;
            }
            else {
                if (i % K == 0 && sb.length() > 0) {
                    sb.append('-');
                }
                i++;
                sb.append(c);
            }
        }
        return sb.toString();
    }

Log in to reply
 

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