LeetCode 482. License Key Formatting #90
quinnwencn
started this conversation in
General
Replies: 1 comment 1 reply
-
AnalysisCreate a new license string by reverse iterating the input license string. The point is when to add dashes to the new license string, Solution written in Cppclass Solution {
public:
string licenseKeyFormatting(string s, int k) {
int n = s.length();
int count = 0;
string result;
for (int i = n - 1; i >= 0; i--) {
if (s[i] != '-') {
if (count == k) {
result.push_back('-');
count = 0;
}
result.push_back(toupper(s[i]));
count++;
}
}
reverse(result.begin(), result.end());
return result;
}
};Solution written in Rustimpl Solution {
pub fn license_key_formatting(s: String, k: i32) -> String {
let mut ret = String::new();
let mut count = 0;
s.chars().rev().for_each(|c| {
if count != k {
if c != '-' {
if count == 0 && ret.len() != 0 {
ret.push('-');
}
ret.push(c.to_uppercase().next().unwrap());
count += 1;
}
}
if count == k {
count = 0;
}
});
ret.chars().rev().collect::<String>()
}
} |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
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 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.
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
Beta Was this translation helpful? Give feedback.
All reactions