Construct Smallest Number From DI String
franklinqin0 StringBacktrackingStackGreedy
# Solution
# Greedy
To match the string DDIDDIDD to the sequence 123456789, reverse all numbers between the points labeled as "I" in the sequence. Every time we encounter an I, we reverse everything from the last split up to (and including) the digit at I.
A step-by-step example:
- Find the first
Iat position 3- Original chunk:
123 - Reverse it:
321 - Partial result:
321
- Original chunk:
- Second
Iat position 6- Next chunk:
456 - Reverse it:
654 - Partial result so far:
321654
- Next chunk:
- Reverse the last group (
789)- Final chunk:
789 - Reverse it:
987
- Final chunk:
Putting it all together, we get: 321654987.
def smallestNumber(self, pattern: str) -> str:
# DDI -> 3214
res = []
stack = []
for i, c in enumerate(pattern+'I', 1):
stack.append(i)
if c == 'I':
res.extend(stack[::-1])
stack = []
return ''.join(map(str, res))
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12