Simple C++ solution


  • 0
    N
    class Solution {
    public:
        string licenseKeyFormatting(string S, int K) {
            string ret = "";
            int n = 0;
            for (int i = 0; i < S.size(); ++ i)
                n += (S[i] != '-');
            int u = 0;
            for (int i = 0; i < n; ++ i){
                while (S[u] == '-') ++ u;
                ret += toupper(S[u]);
                if (((n - i - 1) % K == 0) && (i != n - 1)) ret += '-';
                u ++;
            }
            return ret;
        }
    };
    

    First, count the number of valid characters
    Second, do the work


Log in to reply
 

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