Easy to understand O(n) C++ solution


  • 0
    G
        string licenseKeyFormatting(string S, int K) {
            int alpha_num_cnt = getAlphaNumCnt(S);
            int num_dashes = (alpha_num_cnt - 1) / K;
            string ans_S(alpha_num_cnt + num_dashes, '-');  // initialize the return string with all '-'s
    
            for (int i = S.size() - 1, j = ans_S.size() - 1, cnt = 0; i >= 0; i--) {
                if (S[i] != '-') {
                    char c = islower(S[i]) ? toupper(S[i]) : S[i];
    
                    ans_S[j--] = c;
                    if (++cnt % K == 0) j--;
                }
            }
            return ans_S;
        }
        
        int getAlphaNumCnt(string& S) {
            int cnt = 0;
            for (int i = 0; i < S.size(); i++) {
                if (S[i] != '-') cnt++;
            }
            return cnt;
        }
    

Log in to reply
 

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