-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfindLexSmallestString.cpp
More file actions
40 lines (37 loc) · 1.24 KB
/
findLexSmallestString.cpp
File metadata and controls
40 lines (37 loc) · 1.24 KB
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
class Solution {
public:
string findLexSmallestString(string s, int a, int b) {
string ret = s;
int n = s.size();
for (int k = 0, rotMax = n / std::gcd(n, b); k <= rotMax; ++k) {
s = s.substr(n - b) + s.substr(0, n - b);
string t = s;
int minHead = t[0] - '0';
int count = 0;
if (b & 1) {
for (int i = 0; i < 10; ++i) {
if ((t[0] - '0' + i * a) % 10 < minHead) {
minHead = (t[0] - '0' + i * a) % 10;
count = i;
}
}
for (int i = 0; i < n; i += 2) {
t[i] = (t[i] - '0' + a * count) % 10 + '0';
}
}
minHead = t[1] - '0';
count = 0;
for (int i = 0; i < 10; ++i) {
if ((t[1] - '0' + i * a) % 10 < minHead) {
minHead = (t[1] - '0' + i * a) % 10;
count = i;
}
}
for (int i = 1; i < n; i += 2) {
t[i] = (t[i] - '0' + a * count) % 10 + '0';
}
ret = min(ret, t);
}
return ret;
}
};