Easy understand C++ Solution


  • 0

    Main idea is check the first part and then the left parts with equal length.

     string licenseKeyFormatting(string S, int K) {
            string news,res;
            for(auto ch:S){
                if(ch=='-') continue;
                if(ch>='a'&&ch<='z')
                    news+=ch-32;
                else
                    news+=ch;
            }
            // check first part could be less than K
            int first=news.length()%K;
            // right parts with length K
            int second=news.length()/K;
            if(first){
                res=news.substr(0,first);
                if(second) res+='-';
            }
    
            for(int i=0;i<second;i++){
                for(int j=0;j<K;j++){
                    res+=news[first+i*K+j];
                    if(j==K-1 && i!=second-1) res+='-';
                }
            }
            return res;
        }
    

Log in to reply
 

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