No splitting string or reversing at the end. Simple left to right traverse


  • 0
    V
    public class Solution {
        public string LicenseKeyFormatting(string S, int K) {
            
            var length = GetLength(S);
            if(length == 0) {
                return string.Empty;
            }
            
            int firstset = length % K;
            if(firstset == 0) {
                firstset = K;
            }
            
            var finalString = new StringBuilder();
            
            int i = 0;
            int p = 0;
            while(p < firstset)
            {
                if(S[i] != '-')
                {
                    finalString.Append(S[i].ToString().ToUpper());
                    p++;
                }
                i++;
            }
            
            finalString.Append('-');
            
            while(i < S.Length)
            {
                p = 0;
                while(p < K && i < S.Length)
                {
                    if(S[i] != '-')
                    {
                        finalString.Append(S[i].ToString().ToUpper());
                        p++;
                    }
                    i++;
                }
                if(i < S.Length)
                {
                    finalString.Append('-');
                }
            }
            
            if(finalString[finalString.Length - 1] == '-')
            {
                finalString.Remove(finalString.Length - 1, 1);
            }
            
            return finalString.ToString();
        }
        
        public int GetLength(string str)
        {
            int count = 0;
            for(int i = 0; i < str.Length; i++)
            {
                if(str[i] != '-')
                {
                    count++;
                }
            }
            
            return count;
        }
    }
    
    

Log in to reply
 

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