-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathsolution.cpp
76 lines (74 loc) · 1.78 KB
/
solution.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/**
* 38 / 38 test cases passed.
* Runtime: 540 ms
* Memory Usage: 8 MB
*/
class Solution {
public:
string licenseKeyFormatting(string s, int k) {
string license = "";
for (auto& c: s) {
if (c == '-') continue;
if ('a' <= c && c <= 'z') c -= 32;
license += c;
}
int sz = license.size();
for (int i = sz - k; i > 0; i -= k) {
license.insert(license.begin() + i, '-');
}
return license;
}
};
/**
* 38 / 38 test cases passed.
* Runtime: 4 ms
* Memory Usage: 8.9 MB
*/
class Solution2 {
public:
string licenseKeyFormatting(string s, int k) {
string license = "";
for (auto& c: s) {
if (c == '-') continue;
if ('a' <= c && c <= 'z') c -= 32;
license += c;
}
int sz = license.size();
int first = sz % k;
if (first == 0) first = k;
string ans = license.substr(0, first);
ans += "-";
for (int i = first; i < sz; i += k) {
ans += license.substr(i, k);
ans += "-";
}
if (ans.back() == '-') ans.pop_back();
return ans;
}
};
/**
* 38 / 38 test cases passed.
* Runtime: 8 ms
* Memory Usage: 8 MB
*/
class Solution3 {
public:
string licenseKeyFormatting(string s, int k) {
string ans;
int groups = 0;
for (int i = s.size() - 1; i >= 0; i--) {
if (s[i] != '-') {
ans.push_back(toupper(s[i]));
groups++;
if (groups % k == 0) {
ans.push_back('-');
}
}
}
if (ans.back() == '-') {
ans.pop_back();
}
reverse(ans.begin(), ans.end());
return ans;
}
};