707603. License Key Formatting
Here is the detailed Markdown blog post for the "License Key Formatting" problem:
License Key Formatting
Slug: license-key-formatting Difficulty: Easy Id: 707603 Topic Tags: Strings, Data Structures Company Tags: Google
Summary
Given a string of characters representing a license key, and an array of strings representing the valid characters to be used in the formatted key. The task is to format the given license key by replacing each sequence of k consecutive repeated characters with the character followed by the asterisk (). For example, if the input is "AAABBBCCD" and k = 3, then the output will be "ABCD".
Detailed Explanation
To solve this problem, we can iterate over the given license key and check for each sequence of repeated characters. If the length of the sequence is equal to or greater than k, then replace it with the character followed by the asterisk (*). We use a variable count to keep track of the consecutive repeated characters.
Here's a step-by-step breakdown of the solution:
- Initialize an empty string
resultto store the formatted license key. - Iterate over each character in the given license key.
- For each character, check if it is equal to the previous character. If not, reset the count to 1.
- Increment the count for consecutive repeated characters.
- If the length of the sequence (count) is equal to or greater than k, then append the character followed by the asterisk (*) to the result string and reset the count to 1.
- If the length of the sequence (count) is less than k, then simply append the character to the result string.
- After processing all characters in the license key, return the formatted result.
Time complexity: O(n), where n is the length of the given license key. Space complexity: O(1), as we only use a constant amount of space to store the result and variables.
Optimized Solutions
Java
public String licenseKeyFormatting(String s, int k) {
StringBuilder sb = new StringBuilder();
int count = 0;
for (char c : s.toCharArray()) {
if (c == '-') continue;
if (count >= k) {
sb.append('*');
count = 1;
} else {
sb.append(c);
count++;
}
}
return sb.toString();
}