C# - build in reverse to avoid initial char counting


  • 0

    Here I build the output from the end backwards so you don't have to figure out the first block in advance. However this does require a reverse at the end which is equivalent to a second pass so you could just as easily do the count before building and should be same performance.

    Either way, the key is to avoid any kind of split or insert which are going to slow your performance.

        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.