C++_O(n)_9ms_AC


  • 0
    class Solution {
    public:
    string licenseKeyFormatting(string S, int K) {
        int n = 0;
        for(int i = 0; i < S.size(); ++i){
            if(S[i] == '-'){ continue;}
            else{
                n++;
                if(isalpha(S[i])){
                    S[i] = toupper(S[i]);
                }
            }
        }
        string res = "";
        int num = n/K;
        int f = n - K * (n%K == 0 ? num - 1 : num);
        for(int i = 0; i < S.size();){
            if(S[i] == '-'){i++; continue;}
            if(f){
                res += S[i++];
                f--;
            }else{
                f = K;
                res += '-';
            }
        }
        return res;
    }
    };

Log in to reply
 

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