Java solution


  • 0
    D
    public class Solution {
        public String licenseKeyFormatting(String S, int K) {
            if (S == null || S.length() == 0) {
                return S;
            }
            StringBuffer preprocess = new StringBuffer();
            for (int i = 0; i < S.length(); i++) {
                char ch = S.charAt(i);
                if (ch == '-') {
                    continue;
                }
                if (Character.isLowerCase(ch)) {
                    ch = Character.toUpperCase(ch);
                }
                preprocess.append(ch);
            }
            int len = preprocess.length();
            int firstlen = len % K == 0 ? K : len % K;
            StringBuffer result = new StringBuffer();
            int groups = len / K + (firstlen < K ? 1 : 0);
            for (int group = 0, bIndex = 0; group < groups; group++) {
                for (int i = bIndex; i - bIndex < (group == 0 ? firstlen : K); i++) {
                    result.append(preprocess.charAt(i));
                }
                bIndex += group == 0 ? firstlen : K;
                if (group < groups - 1) {
                    result.append('-');
                }
            }
            return result.toString();
        }
    }
    

Log in to reply
 

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