Lexicographically Smallest String After Applying Operations LeetCode solution in C++

1
class Solution {
2
public:
3
void dfs(string &s, string &small, int a, int b, unordered_map<string, string> &memo) {
4
if (memo.count(s)) return;
5
string res = s, str = res;
6
memo[s] = res;
7
rotate(str.begin(), str.begin() + b, str.end()); // rotate current string
8
dfs(str, small, a, b, memo);
9
if (memo[str] < res) res = memo[str];
10

11
for (int i = 0; i < 9; i++) { // or add it
12
for (int j = 1; j < s.length(); j += 2) s[j] = '0' + ((s[j] - '0') + a) % 10;
13
if (s < res) res = s;
14
dfs(s, small, a, b, memo);
15
}
16
if (small > res) small = res;
17
memo[s] = res;
18
}
19
string findLexSmallestString(string s, int a, int b) {
20
unordered_map<string, string> memo;
21
string res = s;
22
dfs(s, res, a, b, memo);
23
return res;
24
}
25
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0