482. License Key Formatting
Problem Description
You are given a license key represented as a string s that consists of only alphanumeric characters and dashes. The string is separated into n + 1 groups by n dashes. You also get an integer k.
We want to reformat the string s such that each group contains exactly k characters, except for the first group, which could be shorter than k but still must contain at least one character. Furthermore, there must be a dash between two groups, and you should convert all lowercase letters to uppercase.
Return the reformatted license key.
Example 1:
Input: s = "5F3Z-2e-9-w", k = 4
Output: "5F3Z-2E9W"
Explanation: The string s has been split into two parts, each part has 4 characters.
Note that the two extra dashes are not needed and can be removed.
Example 2:
Input: s = "2-5g-3-J", k = 2
Output: "2-5G-3J"
Explanation: The string s has been split into three parts, each part has 2 characters except the first part as it could be shorter as mentioned above.
Constraints:
1 <= s.length <= 10⁵sconsists of English letters, digits, and dashes'-'.1 <= k <= 10⁴
Solution
Python Solution
class Solution:
def licenseKeyFormatting(self, s: str, k: int) -> str:
# Remove all dashes and convert to uppercase
s = s.replace('-', '').upper()
# Calculate length of first group
n = len(s)
first_group_len = n % k if n % k != 0 else k
# Format the string
result = []
# Add first group
if first_group_len > 0:
result.append(s[:first_group_len])
# Add remaining groups
for i in range(first_group_len, n, k):
result.append(s[i:i + k])
# Join groups with dashes
return '-'.join(result)
Time Complexity: O(n)
Where n is the length of the input string.
Space Complexity: O(n)
For storing the reformatted string.
Java Solution
class Solution {
public String licenseKeyFormatting(String s, int k) {
// Remove all dashes and convert to uppercase
s = s.replace("-", "").toUpperCase();
StringBuilder result = new StringBuilder();
int n = s.length();
// Calculate length of first group
int firstGroupLen = n % k;
if (firstGroupLen == 0) {
firstGroupLen = k;
}
// Add first group
if (firstGroupLen > 0) {
result.append(s.substring(0, firstGroupLen));
}
// Add remaining groups
for (int i = firstGroupLen; i < n; i += k) {
if (result.length() > 0) {
result.append('-');
}
result.append(s.substring(i, Math.min(i + k, n)));
}
return result.toString();
}
}
Time Complexity: O(n)
Where n is the length of the input string.
Space Complexity: O(n)
For storing the reformatted string.
C++ Solution
class Solution {
public:
string licenseKeyFormatting(string s, int k) {
// Remove all dashes and convert to uppercase
string clean;
for (char c : s) {
if (c != '-') {
clean += toupper(c);
}
}
string result;
int n = clean.length();
// Calculate length of first group
int firstGroupLen = n % k;
if (firstGroupLen == 0) {
firstGroupLen = k;
}
// Add first group
if (firstGroupLen > 0) {
result = clean.substr(0, firstGroupLen);
}
// Add remaining groups
for (int i = firstGroupLen; i < n; i += k) {
if (!result.empty()) {
result += '-';
}
result += clean.substr(i, k);
}
return result;
}
};
Time Complexity: O(n)
Where n is the length of the input string.
Space Complexity: O(n)
For storing the reformatted string.
JavaScript Solution
/**
* @param {string} s
* @param {number} k
* @return {string}
*/
var licenseKeyFormatting = function(s, k) {
// Remove all dashes and convert to uppercase
s = s.replace(/-/g, '').toUpperCase();
const result = [];
const n = s.length;
// Calculate length of first group
const firstGroupLen = n % k || k;
// Add first group
if (firstGroupLen > 0) {
result.push(s.slice(0, firstGroupLen));
}
// Add remaining groups
for (let i = firstGroupLen; i < n; i += k) {
result.push(s.slice(i, i + k));
}
return result.join('-');
};
Time Complexity: O(n)
Where n is the length of the input string.
Space Complexity: O(n)
For storing the reformatted string.
C# Solution
public class Solution {
public string LicenseKeyFormatting(string s, int k) {
// Remove all dashes and convert to uppercase
s = s.Replace("-", "").ToUpper();
StringBuilder result = new StringBuilder();
int n = s.Length;
// Calculate length of first group
int firstGroupLen = n % k;
if (firstGroupLen == 0) {
firstGroupLen = k;
}
// Add first group
if (firstGroupLen > 0) {
result.Append(s.Substring(0, firstGroupLen));
}
// Add remaining groups
for (int i = firstGroupLen; i < n; i += k) {
if (result.Length > 0) {
result.Append('-');
}
result.Append(s.Substring(i, Math.Min(k, n - i)));
}
return result.ToString();
}
}
Time Complexity: O(n)
Where n is the length of the input string.
Space Complexity: O(n)
For storing the reformatted string.
Approach Explanation
The solution uses string manipulation and formatting:
- Key Insights:
- String cleaning
- Group sizing
- First group handling
- Case conversion
- Algorithm Steps:
- Remove dashes
- Convert to uppercase
- Calculate groups
- Format result
Implementation Details:
- String manipulation
- Group calculation
- Character conversion
- Result building
Optimization Insights:
- Single pass
- Efficient joining
- Memory usage
- String builders
Edge Cases:
- Empty string
- All dashes
- Single character
- Group size variations