C++ Solution without using reverse and/or backward traversal


  • 0
    F
    string licenseKeyFormatting(string S, int K) {
            string result="";
            int len2=0;
            for(int i=0;i<S.length();i++){
                if(S[i]!='-') len2++;
            }        
            if(len2==0)return result;        
            int first=len2%K;
            int first_len=first;
            for(int i=0;i<S.length();i++){           
                while(first>0){
                    if(S[i]!='-'){
                       result=result + (char)toupper(S[i]);
                       first--;                
                    }
                    i++;
                    if(first==0 && len2>first_len){
                        result= result+'-'; 
                        first_len+=1;
                    }                
                }
                if(S[i]!='-'){                
                    if((result.size()-first_len)%(K+1)==K){
                        result= result+'-';
                    }
                    result=result + (char)toupper(S[i]);
                }
            }
            return result;
        }
    

Log in to reply
 

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