题目如下:

解题思路:我用的是递归的方法,每次找出与第一个')'匹配的'('计算atom的数量后去除括号,只到分子式中没有括号为止。例如 "K4(ON(SO3)2)2" -> "K4(ONS2O6)2" -> "K4O2N2S4O12"。接下来再对分子式进行分割,得出每个atom的数量后排序即可。原理很简单,代码写得很乱,仅供参考。

代码如下:

  1. class Solution(object):
  2. def recursive(self,formula):
  3. left = right = None
  4. for i,v in enumerate(formula):
  5. if v == '(':
  6. left = i
  7. elif v == ')':
  8. right = i
  9. break
  10. if left == None and right == None:
  11. return formula
  12. lf = formula[:left]
  13. parse = formula[left+1:right]
  14. times = ''
  15. for i in range(right+1,len(formula)):
  16. if formula[i].isdigit():
  17. times += formula[i]
  18. else:
  19. if i != len(formula) - 1:
  20. i -= 1
  21. break
  22.  
  23. if times != '':
  24. times = int(times)
  25.  
  26. rf = formula[i+1:]
  27.  
  28. if times == '':
  29. ts = parse
  30. else:
  31. parseList = []
  32. val = ''
  33. val_num = ''
  34. parse += '#'
  35. for i in parse:
  36. #print parseList
  37. if i.islower():
  38. val += i
  39. #parseList.append(val)
  40. elif i.isupper():
  41. if val != '':
  42. parseList.append(val)
  43. if val_num != '':
  44. parseList.append(str(int(val_num) * int(times)))
  45. val_num = ''
  46. elif val_num == '' and val != '':
  47. parseList.append(str(times))
  48. val = i
  49. elif i.isdigit():
  50. if val != '':
  51. parseList.append(val)
  52. val = ''
  53. val_num += i
  54. elif i == '#':
  55. if val != '':
  56. parseList.append(val)
  57. if val_num != '':
  58. parseList.append(str(int(val_num) * int(times)))
  59. elif val_num == '' and val != '':
  60. parseList.append(str(times))
  61. ts = ''.join(parseList)
  62. return self.recursive(lf + ts + rf)
  63.  
  64. def countOfAtoms(self, formula):
  65. """
  66. :type formula: str
  67. :rtype: str
  68. """
  69. f = self.recursive(formula)
  70. i = 1
  71.  
  72. #print f
  73.  
  74. #transform MgO2H2 -> Mg1O2H2
  75. while i < len(f):
  76. if f[i].isupper() and f[i-1].isdigit() == False:
  77. f = f[:i] + '' + f[i:]
  78. i = 1
  79. i += 1
  80. if f[-1].isdigit() == False:
  81. f += ''
  82.  
  83. dic = {}
  84.  
  85. key = ''
  86. val = ''
  87.  
  88. # H11He49N1O35B7N46Li20
  89. for i in f:
  90. if i.isdigit():
  91. val += i
  92. else:
  93. if val == '':
  94. key += i
  95. else:
  96. if key not in dic:
  97. dic[key] = int(val)
  98. else:
  99. dic[key] += int(val)
  100. key = i
  101. val = ''
  102.  
  103. if key not in dic:
  104. dic[key] = int(val)
  105. else:
  106. dic[key] += int(val)
  107.  
  108. keys = dic.keys()
  109. keys.sort()
  110. res = ''
  111. #print dic
  112. for i in keys:
  113. res += i
  114. if dic[i] > 1:
  115. res += str(dic[i])
  116. return res

【leetcode】726. Number of Atoms的更多相关文章

  1. 【LeetCode】726. Number of Atoms 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址: https://leetcode.com/problems/number-o ...

  2. 【LeetCode】Largest Number 解题报告

    [LeetCode]Largest Number 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/largest-number/# ...

  3. 【LeetCode】792. Number of Matching Subsequences 解题报告(Python)

    [LeetCode]792. Number of Matching Subsequences 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://f ...

  4. 【LeetCode】673. Number of Longest Increasing Subsequence 解题报告(Python)

    [LeetCode]673. Number of Longest Increasing Subsequence 解题报告(Python) 标签(空格分隔): LeetCode 题目地址:https:/ ...

  5. 【LeetCode】Single Number I & II & III

    Single Number I : Given an array of integers, every element appears twice except for one. Find that ...

  6. 【LeetCode】476. Number Complement (java实现)

    原题链接 https://leetcode.com/problems/number-complement/ 原题 Given a positive integer, output its comple ...

  7. 【LeetCode】191. Number of 1 Bits 解题报告(Java & Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 右移32次 计算末尾的1的个数 转成二进制统计1的个 ...

  8. 【LeetCode】1128. Number of Equivalent Domino Pairs 等价多米诺骨牌对的数量(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 字典统计 代码 复杂度分析 日期 题目地址:http ...

  9. 【LeetCode】447. Number of Boomerangs 解题报告(Java & Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 [LeetCode] 题目地址:https:/ ...

随机推荐

  1. css浮动现象及清除浮动的方法

    css浮动现象及清除浮动的方法   首先先明确浮动最初的定义及使用场景:实现文本环绕图片的效果. 除了用浮动外,目前暂无其他方法实现文本环绕   再来看看浮动的具体定义: 浮动的框可以左右移动,直至它 ...

  2. xiugai-去除js注释

    <div class="myLoading"> <div class="svg-wrap"> <svg width="8 ...

  3. 多行文本溢出隐藏处理,兼容ie,火狐

    问题 多行文本溢出隐藏,webkit内核浏览器如谷歌支持如下写法: overflow: hidden; text-overflow: ellipsis; display: -webkit-box; - ...

  4. MySQL部分索引

    部分索引 char/varchar2太长,全部做索引的话,效率低,浪费存储空间 select avg(length(username)) from 索引统计: show index from tabl ...

  5. docker 保存镜像 加载镜像

    1.保存镜像 docker save -o 保存的文件名  来源镜像 2.加载镜像 docker load -i 保存的文件名

  6. python之环境变量(测试环境可配置)

    想要实现的结果是: 执行脚本时,带一个参数,由这个参数来决定测试环境(开发or测试),比如: python test.py dev 实现代码: 方式1 不用__getitem__方式: import ...

  7. Python——GUI可视化

    import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * class ...

  8. Drone 持续集成实践 - 基于 Gogs,以 Golang 为例

    Drone 官方示例 - Example Go project 用 Docker 部署 Go 服务器 Golang 官方示例 - outyet 一个生产环境的例子 用 rsync 复制文件的方式进行部 ...

  9. poj3614Sunscreen

    Description To avoid unsightly burns while tanning, each of the C (1 ≤ C ≤ 2500) cows must cover her ...

  10. Web控件中Eval()的使用

    1.使用Eval()绑定数据时使用三元运算符 <%#Eval("hg_A").ToString()=="1"?"通过":Eval(&q ...