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
| class Solution {
String smallest = null;
public String findLexSmallestString(String s, int a, int b) {
smallest = s;
Set<String> set = new HashSet<>();
dfs(s, set, a, b);
return smallest;
}
void dfs(String current, Set<String> set, int a, int b) {
if (set.contains(current)) {
return;
}
set.add(current);
if (current.compareTo(smallest) < 0) {
smallest = current;
}
dfs(add(current, a), set, a, b);
dfs(rotate(current, b), set, a, b);
}
String add(String s, int a) {
StringBuilder sb = new StringBuilder(s);
for (int i = 1; i < s.length(); i += 2) {
char c = sb.charAt(i);
int value = c - '0';
value += a;
value = value % 10;
sb.deleteCharAt(i);
sb.insert(i, value);
}
return sb.toString();
}
String rotate(String s, int b) {
int len = s.length();
return s.substring(len - b, len) + s.substring(0, len - b);
}
}
|