Easy and Clean O(n) Java Solution to Understand


  • 0
    J

    public class Solution {

    public String licenseKeyFormatting(String S, int K) {
        char[] c = S.toCharArray();
        StringBuilder sb = new StringBuilder();
        int count = 0;
        for (int i = S.length() - 1; i >= 0; i--) {
            if (c[i] == '-') continue;
            if (count % K == 0) sb.append('-');
            sb.append(c[i]);
            count++;
        }
        
        sb.reverse();
        if (sb.length() > 0) sb.setLength(sb.length() - 1);
        return sb.toString().toUpperCase();
    }
    

    }


Log in to reply
 

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