Skip to content

Commit 377f9b3

Browse files
committed
Time: 812 ms (29.5%), Space: 39.1 MB (8.63%) - LeetHub
1 parent 223dbe0 commit 377f9b3

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# time complexity: O(n*10^n)
2+
# space complexity: O(10^n)
3+
class Solution:
4+
def findLexSmallestString(self, s: str, a: int, b: int) -> str:
5+
result = [s]
6+
visit = set()
7+
8+
def backtrack(s, add, rotate):
9+
if s in visit:
10+
return
11+
visit.add(s)
12+
temp = ''
13+
for i in range(len(s)):
14+
if i % 2:
15+
temp += str((int(s[i]) + add) % 10)
16+
else:
17+
temp += s[i]
18+
if temp < result[0]:
19+
result[0] = temp
20+
backtrack(temp, add, rotate)
21+
s = s[rotate:] + s[:rotate]
22+
if s < result[0]:
23+
result[0] = s
24+
backtrack(s, add, rotate)
25+
return
26+
27+
backtrack(s, a, b)
28+
return result[0]
29+
30+
31+
s = "5525"
32+
a = 9
33+
b = 2
34+
print(Solution().findLexSmallestString(s, a, b))
35+
s = "74"
36+
a = 5
37+
b = 1
38+
print(Solution().findLexSmallestString(s, a, b))
39+
s = "0011"
40+
a = 4
41+
b = 2
42+
print(Solution().findLexSmallestString(s, a, b))

0 commit comments

Comments
 (0)