12 ms Java solution


  • 0
    A
    class Solution {
        public String licenseKeyFormatting(String S, int K) {
            int newLen = 0;
            if (S == null || K == 0) return null;
            for (int i = 0; i < S.length(); i++) {
                if (S.charAt(i) != '-') newLen++;
            }
            newLen = newLen + ((newLen - 1) / K);
            char[] result = new char[newLen];
            int idxFromLast = 0;
            int resultIdx = result.length - 1;
            for (int i = S.length() - 1; i >= 0; i--) {
                if (idxFromLast != 0 && (idxFromLast % K == 0) && resultIdx >= 0) { result[resultIdx--] = '-'; idxFromLast = 0;}
                char c = S.charAt(i);
                if (c == '-') { continue; }
                if (c >= 'a' && c <= 'z') result[resultIdx--] = (char) ('A' + c - 'a');
                else result[resultIdx--] = c;
                idxFromLast++;
            }
            return new String(result);
        }
    }
    

Log in to reply
 

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