Java Solution - LicenseKey Formatting


  • 0
    M
    public String licenseKeyFormatting(String S, int K) {
    
            if (K <= 0)
                return "";
    
            String result = (S.replaceAll("-", "")).toUpperCase();
    
            int numDashes = 0, startIndex = 0;
    
            if (result.length() % K == 0) {
    
                numDashes = result.length() / K - 1;
                startIndex = K;
            } else {
    
                numDashes = (int) result.length() / K;
                startIndex = result.length() % K;
            }
    
            StringBuilder output = new StringBuilder(result);
    
    
            for (int i = 0; i < numDashes; i++) {
                output.insert(startIndex, '-');
                startIndex += K + 1;
            }
    
            return new String(output);
    
        }

Log in to reply
 

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