Easy Understand Java solution using StringBuilder


  • 2
    Z
    public class Solution {
        public String licenseKeyFormatting(String S, int K) {
            String[] strs = S.split("-");
            StringBuilder rst = new StringBuilder();
            int gap = 'A' - 'a';
            
            for (String str : strs) {
                rst.append(str);
            }
            
            int len = rst.length();
            
            for (int i = 0; i < len; i++) {
                char c = rst.charAt(i);
                if (c>='a' && c<='z') {
                    rst.setCharAt(i, (char)(c+gap));
                }
            }
    
            for (int i = len-K; i > 0; i -= K) {
                rst.insert(i, '-');
            }
            return rst.toString();
        }
    }
    

  • 0

    Here's one that avoids both string split which creates extra memory for string array and StringBuilder insert which is an O(n) operation. The trick to single pass is to work backwards, which does require a reverse at the end of the routine.

        public string LicenseKeyFormatting(string S, int K) 
        {
            StringBuilder sb = new StringBuilder();
            int charLen = 0;
            for (int i = S.Length - 1; i >= 0; i--)
            {
                if (S[i] != '-')
                {
                    if (charLen > 0 && charLen % K == 0)
                    {
                        sb.Append('-');
                    }
                    sb.Append(Char.ToUpper(S[i]));
                    charLen++;
                }
            }
            
            char[] chars = sb.ToString().ToCharArray();
            Array.Reverse(chars);
            return new string(chars);
        }
    

Log in to reply
 

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