Sponsored
Sponsored
This approach involves first cleaning up the input string by removing all non-alphanumeric characters and converting it to uppercase. Then, starting from the end of the string, we build the new license key by appending groups of size k
. This is achieved using a StringBuilder
for efficient string manipulation.
Time Complexity: O(n), where n is the length of the string s
. Space Complexity: O(n) due to the additional storage requirements for the new formatted string.
1function licenseKeyFormatting(s, k) {
2 s = s.replace(/-/g, '').toUpperCase();
3 let n = s.length;
4 let remainder = n % k;
5 let groups = [];
6 if (remainder > 0) {
7 groups.push(s.substring(0, remainder));
8 }
9 for (let i = remainder; i < n; i += k) {
10 groups.push(s.substring(i, i + k));
11 }
12 return groups.join('-');
13}
Similar to the Python solution, we first strip out non-alphanumeric characters and convert the string to uppercase. The remainder and looping strategy are the same, ensuring that all groups after the first are of equal length k
.
This method suggests reversing the cleaned-up string to easily extract groups from the end, and then reversing the result at the end. This eliminates the need for calculating the remainder at the start and allows straightforward appending of characters.
Time Complexity: O(n), where n is the length of s
. Space Complexity: O(n) for storing the result string temporarily.
1class Solution {
2 public String licenseKeyFormatting
By reversing the process, we simplify grouping into steps of k
directly from the end without needing any special handling for the first group. We maintain a counter to insert a dash after every k
characters and finally reverse the accumulated result.