
Problem Statement
You are presented with a license key represented by a string that includes alphanumeric characters and dashes. This string is segmented into several groups using dashes. Additionally, you are given an integer value k
which determines the size of each group in the license key after reformatting.
The goal is to reformat this license key so that every group contains exactly k
characters. The exception is the first group, which may contain fewer than k
characters but must contain at least one character. Each group should be separated by a single dash in the reformatted string. Moreover, all lowercase letters in the original string should be converted to uppercase. By processing these transformations, you must return a newly formatted license key string.
Examples
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 <= 105
s
consists of English letters, digits, and dashes'-'
.1 <= k <= 104
Approach and Intuition
Remove all dashes and capitalize: Start by cleansing the input string
s
:- Remove all dashes.
- Convert all letters to uppercase.
Determine the length and first group size: Calculate the full length of the modified string (without dashes):
- Identify the size of the first group, which can be calculated as the remainder of the length of the string when divided by
k
. - If there's no remainder (i.e., the string length is perfectly divisible by
k
), set the first group's size tok
.
- Identify the size of the first group, which can be calculated as the remainder of the length of the string when divided by
Rebuild the string with grouped dashes: Construct the new license key:
- Start by adding the first group to the result.
- Then for every subsequent group of size
k
, add a dash followed by the nextk
characters from the string.
Return the formatted license key: The string formed by the above steps gives the final reformatted license key.
Solutions
- C++
- Java
- JavaScript
class Solution {
public:
string formatLicenseKey(string str, int n) {
int validChars = 0;
for (int j = 0; j < str.length(); j++) {
if (str[j] != '-') {
validChars++;
}
}
int firstGroupSize = (validChars % n);
if (firstGroupSize == 0) {
firstGroupSize = n;
}
string result = "";
int index = 0;
int countCharacters = 0;
while (index < str.length()) {
if (countCharacters == firstGroupSize) {
countCharacters = 0;
break;
}
if (str[index] != '-') {
countCharacters++;
result.push_back(toupper(str[index]));
}
index++;
}
if (index >= str.length()) {
return result;
}
result.push_back('-');
while (index < str.length()) {
if (str[index] != '-') {
if (countCharacters == n) {
result.push_back('-');
countCharacters = 0;
}
result.push_back(toupper(str[index]));
countCharacters++;
}
index++;
}
return result;
}
};
The provided C++ function, formatLicenseKey
, reformats a given string representing a license key. It focuses on accepting two parameters: str
, the license key string to format, and n
, determining the desired group length following the first segment. The function structures the key by grouping characters (excluding dashes) into segments of length specified. The entire process includes:
- Counting non-dash characters to decide the total number of valid characters in the input.
- Calculating the size of the initial group which could be smaller than
n
ifvalidChars % n
isn't zero; otherwise, it isn
. - Iterating through the string to first fill the initial group:
- Characters are added to the
result
after converting them to uppercase, ensuring to exclude dashes. - Once the first group reaches its desired size, a dash is appended as a separator if not at the end of the string.
- Characters are added to the
- Continue processing the rest of the string:
- For subsequent characters, groups of
n
characters are formed, separated by a dash. - Each valid character, not being a dash, is converted to uppercase before appending to the result.
- For subsequent characters, groups of
The key takeaway from the function is efficient management and transformation of the input string into the desired formatted output while ensuring correct groupings and handling of characters. The final result string is returned containing the formatted license key with specified groupings clearly separated by dashes.
class Formatter {
public String formatLicenseKey(String input, int groupSize) {
int alphaNumChars = 0;
for (int index = 0; index < input.length(); index++) {
if (input.charAt(index) != '-') {
alphaNumChars++;
}
}
int firstGroupLength = (alphaNumChars % groupSize);
if (firstGroupLength == 0) {
firstGroupLength = groupSize;
}
StringBuilder formattedKey = new StringBuilder();
int currentIndex = 0;
int currentCount = 0;
while (currentIndex < input.length()) {
if (currentCount == firstGroupLength) {
currentCount = 0;
break;
}
if (input.charAt(currentIndex) != '-') {
currentCount++;
formattedKey.append(Character.toUpperCase(input.charAt(currentIndex)));
}
currentIndex++;
}
if (currentIndex >= input.length()) {
return formattedKey.toString();
}
formattedKey.append('-');
while (currentIndex < input.length()) {
if (input.charAt(currentIndex) != '-') {
if (currentCount == groupSize) {
formattedKey.append('-');
currentCount = 0;
}
formattedKey.append(Character.toUpperCase(input.charAt(currentIndex)));
currentCount++;
}
currentIndex++;
}
return formattedKey.toString();
}
}
The provided Java code demonstrates a method to reformat a given license key string based on a specified group size. The code involves several steps:
- Define a method
formatLicenseKey
in theFormatter
class that accepts aString input
representing the unformatted license key and anint groupSize
which determines how many characters each group in the formatted key should contain. - Compute the number of alphanumeric characters in the input string by iterating over each character and counting characters other than dashes.
- Determine the length of the first group, which can differ from the subsequent groups if the total number of alphanumeric characters isn't a multiple of
groupSize
. - Use a
StringBuilder
to construct the formatted license key. - Start looping through the string, skipping dashes and converting characters to uppercase before adding them to the
StringBuilder
. Implement logic to add a dash after completing each group, ensuring the first group adheres to its computed unique size if applicable. - Return the complete and formatted string after processing all characters in the input string.
This method effectively handles the formatting of license keys by grouping characters according to the specified groupSize
, adjusting for cases where not all groups can be the same size and ensuring the use of uppercase letters, providing a standard format common in software license keys and other similar formats.
var formatLicenseKey = function(inputStr, groupSize) {
let characterCount = 0;
for (let index = 0; index < inputStr.length; index++) {
if (inputStr.charAt(index) != '-') {
characterCount++;
}
}
let firstGroupLength = (characterCount % groupSize);
if (firstGroupLength == 0) {
firstGroupLength = groupSize;
}
let formattedKey = "";
let index = 0;
let currentCount = 0;
while (index < inputStr.length) {
if (currentCount == firstGroupLength) {
currentCount = 0;
break;
}
if (inputStr.charAt(index) != '-') {
currentCount++;
formattedKey += inputStr.charAt(index).toUpperCase();
}
index++;
}
if(index >= inputStr.length) {
return formattedKey;
}
formattedKey += '-';
while (index < inputStr.length) {
if (inputStr.charAt(index) != '-') {
if (currentCount == groupSize) {
formattedKey += '-';
currentCount = 0;
}
formattedKey += inputStr.charAt(index).toUpperCase();
currentCount++;
}
index++;
}
return formattedKey;
}
The provided JavaScript function handles the formatting of a license key string according to specified group sizes. The function formatLicenseKey
receives two parameters: inputStr
, which is the unformatted license key as a string, and groupSize
, an integer defining the size of each group of characters in the formatted key except possibly the first group.
Here’s a step-by-step explanation of the code:
Initialize
characterCount
to zero. Iterate throughinputStr
and count the alphanumeric characters, skipping dashes.Calculate the length of the first group:
- If the total count of characters modulo the
groupSize
is zero, then the first group's length is equal togroupSize
. - Otherwise, it is the remainder of
characterCount
divided bygroupSize
.
- If the total count of characters modulo the
Initialize variables for the formatted key (
formattedKey
), the index of the current character ininputStr
, and a counter (currentCount
) for characters added to theformattedKey
.Construct the first group of characters by converting each to uppercase and appending it to
formattedKey
until the length of the first group is reached.If all characters are processed during the first group construction, return
formattedKey
.Append a dash to separate the first group from the next.
Continue processing the rest of
inputStr
by appending each character (converted to uppercase) toformattedKey
. Add dashes between groups when the count reaches the specifiedgroupSize
.
The function returns the formatted key after appending all the characters correctly grouped and in uppercase. This approach ensures that the initial part of the key may have a different grouping than the subsequent parts if characterCount
isn't exactly divisible by groupSize
. The format ensures all groups after the first adhere strictly to the groupSize
specification.
No comments yet.