4-line C++ concise solution to scan string backward


  • 7

    Key observation: every (K+1)th character from the tail of the formatted string must be a '-'.

        string licenseKeyFormatting(string S, int K) {
          string res;
          for (auto i = S.rbegin(); i < S.rend(); i++)
            if (*i != '-') (res.size()%(K+1)-K? res : res+='-') += toupper(*i);
          return reverse(res.begin(), res.end()), res;
        }
    

    A rewritten version for readability:

        string licenseKeyFormatting(string S, int K) {
          string res;
          for (auto i = S.rbegin(); i < S.rend(); i++)
            if (*i != '-') { // ignore '-' in original string
              if (res.size()%(K+1) == K) res += '-'; // every (K+1)th char is '-' from tail
              res += toupper(*i);
            }
            
          reverse(res.begin(), res.end());
          return res;
        }
    

  • 0
    A
    This post is deleted!

  • 1

    Thanks for your sharing. But your code is hard to read. You can write all code in one line and say it's a 1-line solution. It's not helpful. :(


  • 0

    @programiao You are totally right. I actually only do this in OJ for "fun" as coding problems. It would be terrible and hard for maintenance in my actual work.

    A rewritten version added for readability.


  • 0
    S

    A more readable version of same code.

    string licenseKeyFormatting(string S, int K) {
        string new_string;
        int num_of_chars_after_dash = 0;
        for (int i = S.length() - 1; i >= 0; i--) {
            if (S[i] != '-') {
                if (num_of_chars_after_dash!=0 && num_of_chars_after_dash % K == 0) {
                    new_string = new_string + '-';
                    num_of_chars_after_dash = 0;
                }
                new_string = new_string + (char)toupper(S[i]);
                num_of_chars_after_dash++;
            }
        }
        reverse(new_string.begin(), new_string.end());
        return new_string;
    }
    

Log in to reply
 

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