[Geeks for Geeks] License Key Formatting

License Key Formatting

Given a string S that consists of only alphanumeric characters and dashes. The string is separated into N + 1 groups by N dashes. 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 string.

  • Time : O(n)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
char convert(char ch) {
if('0' <= ch and ch <= '9') return ch;
if('A' <= ch and ch <= 'Z') return ch;
return ch - 'a' + 'A';
}
public:
string ReFormatString(string S, int K) {
string res = "";
for (int i = S.length() - 1, split = 0; i >= 0; i--) {
if (S[i] == '-') continue;
res.push_back(convert(S[i]));
if (res.length() - split == K) {
res.push_back('-');
split = res.length();
}
}
if (res.back() == '-') res.pop_back();
reverse(begin(res), end(res));
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/27/PS/GeeksforGeeks/license-key-formatting/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.