How-To
- #!/usr/bin/env python3
- class Solution:
- def diStringMatch(self, S):
- r'''
- IDID
- IDID -> 02143
- III
- III -> 0123
- DDI
- DDI -> 3214
- Solution:
- Find ranges of D and reverse the numbers within that range.
- For example:
- 1) Find range of D
- IDID => [(1, 2), (3, 4)]
- 2) Reverse the D range
- -- --
- (1, 2) => 01234 -> 02134
- -- --
- (3, 4) => 02134 -> 02143
- '''
- s_len = len(S)
- plist = list(range(s_len + 1))
- # 1) Collecting reverse tuple
- rt_list = []
- i = 0
- while i < len(S):
- if S[i] == 'D':
- dpair = [i]
- for j in range(i+1, s_len):
- if S[j] == 'D':
- i += 1
- else:
- break
- i += 1
- dpair.append(i)
- rt_list.append(dpair)
- else:
- i += 1
- # 2) Work on reverse tuple
- for rt in rt_list:
- plist[rt[0]:rt[1]+1] = plist[rt[0]:rt[1]+1][::-1]
- print('S={}; rt_list={}; plist={}'.format(S, rt_list, plist))
- return plist
* FAQ - How do I reverse a part (slice) of a list in Python?
沒有留言:
張貼留言