Java Clean Solution

  • 0

    Because the problem ignore the length limit for first group, we can start process the string from the end of string. As String in Java is immutable, StringBuilder is preferred here.

    Here are the rules to process the input in the for loop starting from right side of the string

    • continue the for loop if '-' met
    • if current size of StringBuilder mod k+1 equals to k, append a '-'
    • if current char is letter, convert it to upper case. Otherwise, append it directly.

    After the for loop, we can just reverse the StringBuilder to get the result.
    Here is the code:

    public String licenseKeyFormatting(String S, int K) {
        StringBuilder sb = new StringBuilder();
        for (int i = S.length() - 1; i >= 0; i--) {
            if (S.charAt(i) == '-') {
            // append "-" before append the last character
            if (sb.length() % (K+1) == K) sb.append("-");
            sb.append(Character.isLetter(S.charAt(i)) ? Character.toUpperCase(S.charAt(i)) : S.charAt(i));
        // reverse the string
        return sb.reverse().toString();

    Time complexity: o(n) as the pointer would traverse the string one time.
    Space complexity: o(n) for the size of StringBuilder.

Log in to reply

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