-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path482.cpp
50 lines (50 loc) · 1.12 KB
/
482.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// smarter-6ms.cpp
class Solution {
public:
string licenseKeyFormatting(string S, int K) {
string res;
int count = 0;
for (auto it = S.rbegin(); it != S.rend(); ++it)
if (*it != '-') {
if (count++ == K) {
count = 1;
res += '-';
}
res += toupper(*it);
}
return string(res.rbegin(), res.rend());
}
};
// stupid-9ms.cpp
class Solution2 {
public:
string licenseKeyFormatting(string S, int K) {
int dashNumber = 0;
for (auto ch : S)
if (ch == '-')
++dashNumber;
int charNumber = S.size() - dashNumber;
int headSize = charNumber % K;
string res;
int i = 0, j = 0;
for (; i < headSize; ++j)
if (S[j] != '-') {
res += S[j] >= 'a' && S[j] <= 'z' ? S[j] + 'A' - 'a' : S[j];
++i;
}
if (headSize)
res += '-';
for (i = 0; j < S.size(); ++j) {
if (S[j] != '-') {
res += S[j] >= 'a' && S[j] <= 'z' ? S[j] + 'A' - 'a' : S[j];
if (++i == K) {
i = 0;
res += '-';
}
}
}
if (res.back() == '-')
res.pop_back();
return res;
}
};