Simple Javascript Pointer


  • 0
    J

    Scan backwards through the cleaned and uppercased string, updating the pointer of the next place to insert the - symbol.

    /**
     * @param {string} S
     * @param {number} K
     * @return {string}
     */
    var licenseKeyFormatting = function(String, K) {
        var licenseKey = '';
        var cleanedString = String.replace(/-/g, '', '').toUpperCase();
        var position = cleanedString.length - K;
        
        for (i = cleanedString.length - 1; i >= 0; i--) {
            
            licenseKey += cleanedString[i];
        
            if (i === position && position !== 0) {
                licenseKey += '-';
                position -= K;
            }
        }
        return licenseKey.split('').reverse('').join('');
    };
    

Log in to reply
 

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