1. 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.
constraints :
- 1 <= s.length <= \(10^{5}\)
- s consists of English letters, digits, and dashes '-'.
- 1 <= k <= \(10^{4}\)
2. Algorithms
There are three points to focus.
- The string is separated into n + 1 groups by n dashes.
- First group could be shorter than k but still must contain at least one character.
- All lowercase letters should be converted into uppercase.
For example, Let's think abouth when input s is "2-5g-3-J" and input k is 2. Our information for solving algorithm will be same as below.
- The total string without "-" : "25g3J"
- The total length of converted string : 5
- The value of input k : 2
- The combinations of each group for reformatting : 1 + 2 + 2
So, when we reformat our input string s, we need to consider the length of first group. When the total length of converted string can be divided by k, then the length of first group will be k too. If the total length of converted string cannot be divided by k, then the length of first group will be the length of total mod k.
- Start
- Convert the input string s, splitting by "-" and join them in one. ("".join(s.split("-")))
- Calcluate the total length of converted string and store the result in variable named n. (n = len(s))
- Declare result variable named res and initialize to empty string.
- If the remainder of n mod k is zero (n % k == 0),
- Update substring group incrementing index by k in range 0 - n.
- Else, calculate the remainder of n divide k. (r = n % k)
- Update first group which final index is r.
- Update substring group incrementing index by k in range 0 - n.
- Return the result without final element and convert lowercase to uppercase.
- End
3. Codes
class Solution:
def licenseKeyFormatting(self, s: str, k: int) -> str:
s = "".join(s.split("-"))
n = len(s)
res = ""
# Check the length of first group for reformatting.
# if k is divisor of n, the length of first group will be k.
# if not, the length of first group will be n % k.
if n % k == 0 :
for i in range(0, n, k) :
res += s[i:i+k] + "-"
else :
r = n % k
res += s[:r] + "-"
for i in range(r, n, k) :
res += s[i:i+k] + "-"
return res[:-1].upper()
4. Conclusion
'LeetCode > Easy' 카테고리의 다른 글
492 Construct the Rectangle (0) | 2022.08.31 |
---|---|
485 Max Consecutive Ones (0) | 2022.08.31 |
476 Number Complement (0) | 2022.08.31 |
463 Island Perimeter (0) | 2022.08.31 |
461 Hamming Distance (0) | 2022.08.30 |