Easy to understand O(n) time O(n) space solution.


  • 0
    H
    class Solution {
    public:
        string licenseKeyFormatting(string S, int K) {
         
            if (S.size() == 0 || K == 0) return "";
            string ret = "";
            
            int k = 0;
            for(int i = S.size()-1; i >= 0; i--) {
                if (S[i] == '-') continue;
                if (K == k) {ret = "-" + ret; k = 0; i++;}
                else {ret = static_cast<char>(toupper(S[i])) + ret; k++;}
            }
        
            return ret;
        }
    };
    

Log in to reply
 

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