中级农民
- 积分
- 104
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2014-11-9
- 最后登录
- 1970-1-1
|
第六题用递归的方式写了一下
- def process(str, start, end, parenthesisMatch):
- # Separate the string by commas on the same level
- i, j = start, start
- list = []
- while j <= end:
- if str[j] == ',':
- list.append((i, j))
- i = j + 1
- elif str[j] == '{':
- j = parenthesisMatch[j]
- j += 1
- if i<j:
- list.append((i, j))
-
- # Parse each separated string (recursive)
- res = []
- for i, j in list:
- if str[i:j].isalpha():
- res.append(str[i:j])
- else:
- ii, jj = i, i
- super = [""]
- while jj<j:
- if str[jj] == '{':
- res_before = process(str, ii, jj-1, parenthesisMatch)
- res_in_paren = process(str, jj+1, parenthesisMatch[jj]-1, parenthesisMatch)
- if res_before:
- for k in range(len(res_in_paren)):
- res_in_paren[k] = res_before[0] + res_in_paren[k]
- super_new = []
- for s in super:
- for t in res_in_paren:
- super_new.append(s+t)
- super = super_new
- jj = parenthesisMatch[jj]
- ii = jj + 1
- jj += 1
- if ii<jj:
- for k in range(len(super)):
- super[k] += str[ii:jj]
- res.extend(super)
- return res
- def interpret(str):
- parenthesisMatch = {} # Key: index of left parenthesis, value: index of right parenthesis
- stack = []
- for i, c in enumerate(str):
- if c == '{':
- stack.append(i)
- elif c == '}':
- parenthesisMatch[stack.pop()] = i
- return process(str, 0, len(str) - 1, parenthesisMatch)
-
- print(interpret('{a,b}x{c,d}y{e,f{g,h}{i,j}k}'))
复制代码 |
|