leetcode 482. License Key Formatting

Orignal question can be found here.

My solution is as follows:

char* licenseKeyFormatting(char* S, int K)
{
  int s_len = strlen(S);
  int len = 0;
  for(int i=0; i<s_len; ++i)
    {
      if(S[i] != '-')
        ++len;
    }
  int result_len = 0;
  int cur = 0;
  if(len<=K)
    {
      char *res = (char *)malloc((len+1) * sizeof(char));
      res[len] = 0;
      for(int i=0; i<s_len; ++i)
        {
          if(S[i] != '-')
            {
              if(S[i]>='a' && S[i]<='z')
                res[cur] = S[i] - 'a' + 'A';
              else
                res[cur] = S[i];
              ++cur;
            }
        }
      return res;
    }
  if(len%K== 0)
    result_len = len/K+len-1;
  else
    result_len = len/K+len;
  char *result = (char *)malloc((result_len+1) * sizeof(char));
  result[result_len] = 0;

  cur = 0;
  for(int i=s_len-1; i>=0; --i)
    {
      if(S[i] != '-')
        {
          if((cur+1)%(K+1) == 0)
            {
              result[result_len - 1 - cur] = '-';
              ++cur;
            }
          if(S[i]>='a' && S[i]<='z')
            result[result_len -1 - cur] = S[i] - 'a' + 'A';
          else
            result[result_len -1 - cur] = S[i];
          ++cur;
        }
    }
  return result;
}

Leave a Reply

Your email address will not be published. Required fields are marked *