In this Leetcode License Key Formatting problem solution You are given a license key represented as a string s that consists of only alphanumeric characters and dashes. The string is separated into n + 1 groups by n dashes. You are also given an integer k.

We want to reformat the string s such that each group contains exactly k characters, except for the first group, which could be shorter than k but still must contain at least one character. Furthermore, there must be a dash inserted between two groups, and you should convert all lowercase letters to uppercase.

Return the reformatted license key.

Leetcode License Key Formatting problem solution


Problem solution in Python.

class Solution(object):
    def licenseKeyFormatting(self, S, K):
        s = S.replace('-', '').upper()
        ngroups, rem = len(s) / K , len(s) % K
        S = s[0:rem]
        for i in range(ngroups):
            if i > 0 or rem > 0: S += '-'
            S += s[rem+i*K:rem+(i+1)*K]
        return S

Problem solution in Java.

public String licenseKeyFormatting(String S, int K) {
        StringBuilder sb = new StringBuilder(); 
        S = S.replace("-", ""); 
        S = S.toUpperCase();
        if (S.length() == 0) {
            return S; 
        }
        int i = S.length() - 1; 
        while (i >= 0) {
            int count = 0; 
            while (count < K && i >= 0) {
                count++; 
                sb.append(S.charAt(i--)); 
            }
            sb.append("-"); 
        }
        
        sb.deleteCharAt(sb.length() - 1); 
        return sb.reverse().toString(); 
    }


Problem solution in C++.

string licenseKeyFormatting(string S, int K) {
        if (S.empty()) return S;
 
        std::string key;
        key.reserve(2*S.length());
        int len = 0;
        for_each(S.rbegin(), S.rend(), [&](char c)
        {
            if (c != '-')
            {
                if(len == K)
                {
                    key += "-";
                    len = 0;
                }
                ++len;
                key += std::toupper(c);
            }
        });
        std::reverse(key.begin(), key.end());
        return key;
        
    }