C++ Easy to understand solution using backward traversal and transform().


  • 0
    A
    class Solution {
    public:
        string licenseKeyFormatting(string s, int k) {
                    string res;
    		int i = s.size()-1;
    		int cnt = k;
    		while (i >= 0) 
    		{
    			if (s[i] != '-') 
    			{
    			    res.push_back(s[i]);
    		            cnt--;
    			}
    			if (cnt == 0) 
    			{
    			    res.push_back('-');
    			    cnt = k;
    			}
    		    i--;
    		}
    		if (res.back() == '-') {
    			res.pop_back();
    		}
    	     reverse(res.begin(),res.end());
                 std::transform(res.begin(), res.end(), res.begin(), ::toupper);
    	     return res;
        }
    };
    
    

Log in to reply
 

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