Java solution

  • 0
        public String licenseKeyFormatting(String S, int K) {
            StringBuilder sb = new StringBuilder();
            // Make a copy so we are not modifying the string passed in
            // Remove the '-' when making the copy because we're going to add them ourselves
            String string = new String(S.replaceAll("-", ""));
            int counter = 0;
            // Iterate through the string starting at the end, that way we can count K characters and 
            // then add the - in the correct place.
            // Note: we're decrementing since we're starting at the end of the string
            for(int i = string.length() - 1; i >= 0; i--) {
                // Requirement is for all characters to be Uppercase
                // Add a - for every K characters we've added, except if we are at the first character of 
                // the string
                if(counter == K && i != 0) {
                    counter = 0;
            // The last step is to reverse the string so it is returned in the correct order
            return sb.reverse().toString();

Log in to reply

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