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;
    }

    ranges::reverse(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();
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
  def licenseKeyFormatting(self, s: str, k: int) -> str:
    ans = []
    length = 0

    for i in reversed(range(len(s))):
      if s[i] == '-':
        continue
      if length > 0 and length % k == 0:
        ans += '-'
      ans += s[i].upper()
      length += 1

    return ''.join(reversed(ans))