Java straight forward solution


  • 0
    J
        public String licenseKeyFormatting(String S, int K) {
            StringBuilder sb = new StringBuilder();
            int cnt = 0;
            boolean needDash = false;
            for (int i = S.length() - 1; i >= 0; i--) {
                char c = S.charAt(i);
                if (c == '-') continue;
                cnt++;
                if (c >= 'a' && c <= 'z') c = (char) (c - 'a' + 'A');
                if (needDash) {
                    sb.append('-');
                    needDash = false;
                }
                sb.append(c);
                if (cnt % K == 0 && i > 0) needDash = true; 
            }
            return sb.reverse().toString();
        }
    

Log in to reply
 

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