LeetCode 482: License Key Formatting Solution
Master LeetCode problem 482 (License Key Formatting), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
482. License Key Formatting
Problem Explanation
Explanation
To solve this problem, we can follow these steps:
- Remove all dashes from the input string and convert all lowercase letters to uppercase.
- Calculate the length of the first group by finding the remainder when dividing the length of the modified string by k.
- Create a new string by iterating through the modified string and inserting dashes after every k characters, except for the first group.
- Return the reformatted license key.
Time complexity: O(n) where n is the length of the input string s. Space complexity: O(n) for storing the modified string.
Solution Code
class Solution {
public String licenseKeyFormatting(String s, int k) {
StringBuilder sb = new StringBuilder();
for (char c : s.toCharArray()) {
if (c != '-') {
sb.append(Character.toUpperCase(c));
}
}
int firstGroupLen = sb.length() % k;
StringBuilder res = new StringBuilder();
int i = 0;
while (i < sb.length()) {
if (i > 0 && (i - firstGroupLen) % k == 0) {
res.append('-');
}
res.append(sb.charAt(i));
i++;
}
return res.toString();
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 482 (License Key Formatting)?
This page provides optimized solutions for LeetCode problem 482 (License Key Formatting) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 482 (License Key Formatting)?
The time complexity for LeetCode 482 (License Key Formatting) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 482 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 482 in Java, C++, or Python.