Concise Java Solution


  • 0
    H
    public String licenseKeyFormatting(String S, int K) {
            if(S==null) return null;
            
            int length = 0;
    // get the number of non-dash letters.
            for(int i = 0 ; i<S.length() ; i++) if(S.charAt(i)!='-') length++;
            
            StringBuilder sb = new StringBuilder();
            int count = 0;
            for(int i = 0; i<S.length() ; i++)
            {
                if(S.charAt(i)!='-')
                {
                    if(count%K == length%K ) sb.append('-');
                    sb.append(Character.toUpperCase(S.charAt(i)));
                    count++;
                }
            }
            // if length%k == 0, then the first char will be '-'. delete it.
            if(sb.length()>0 && sb.charAt(0)=='-') sb.deleteCharAt(0);
            return sb.toString();
        }
    

Log in to reply
 

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