Skip to content

482. License Key Formatting 👎

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  string licenseKeyFormatting(string S, int K) {
    string ans;
    int length = 0;

    for (int i = S.length() - 1; i >= 0; --i) {
      if (S[i] == '-')
        continue;
      if (length > 0 && length % K == 0)
        ans += "-";
      ans += toupper(S[i]);
      ++length;
    }

    reverse(begin(ans), end(ans));
    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
  public String licenseKeyFormatting(String S, int K) {
    StringBuilder sb = new StringBuilder();
    int length = 0;

    for (int i = S.length() - 1; i >= 0; --i) {
      if (S.charAt(i) == '-')
        continue;
      if (length > 0 && length % K == 0)
        sb.append('-');
      sb.append(Character.toUpperCase(S.charAt(i)));
      ++length;
    }

    return sb.reverse().toString();
  }
}