#482
Easy Algorithms License key formatting
String
45.7% acceptance
Jan 13, 2026
1197
1463
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 are also given 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 inserted between two groups, and you should convert all lowercase letters to uppercase.
Return the reformatted license key.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn license_key_formatting(s: String, k: i32) -> String {
let chars: String = s.chars().filter(|&c| c != '-').map(|c| c.to_ascii_uppercase()).collect();
let len = chars.len();
if len == 0 { return String::new(); }
let first_group_size = len % k as usize;
let mut result = String::new();
if first_group_size > 0 {
result.push_str(&chars[..first_group_size]);
if first_group_size < len {
result.push('-');
}
}
let mut i = first_group_size;
while i < len {
result.push_str(&chars[i..i + k as usize]);
i += k as usize;
if i < len {
result.push('-');
}
}
result
}
}