题目如下:

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

代码如下:

class Solution(object):
def recursive(self,formula):
left = right = None
for i,v in enumerate(formula):
if v == '(':
left = i
elif v == ')':
right = i
break
if left == None and right == None:
return formula
lf = formula[:left]
parse = formula[left+1:right]
times = ''
for i in range(right+1,len(formula)):
if formula[i].isdigit():
times += formula[i]
else:
if i != len(formula) - 1:
i -= 1
break if times != '':
times = int(times) rf = formula[i+1:] if times == '':
ts = parse
else:
parseList = []
val = ''
val_num = ''
parse += '#'
for i in parse:
#print parseList
if i.islower():
val += i
#parseList.append(val)
elif i.isupper():
if val != '':
parseList.append(val)
if val_num != '':
parseList.append(str(int(val_num) * int(times)))
val_num = ''
elif val_num == '' and val != '':
parseList.append(str(times))
val = i
elif i.isdigit():
if val != '':
parseList.append(val)
val = ''
val_num += i
elif i == '#':
if val != '':
parseList.append(val)
if val_num != '':
parseList.append(str(int(val_num) * int(times)))
elif val_num == '' and val != '':
parseList.append(str(times))
ts = ''.join(parseList)
return self.recursive(lf + ts + rf) def countOfAtoms(self, formula):
"""
:type formula: str
:rtype: str
"""
f = self.recursive(formula)
i = 1 #print f #transform MgO2H2 -> Mg1O2H2
while i < len(f):
if f[i].isupper() and f[i-1].isdigit() == False:
f = f[:i] + '' + f[i:]
i = 1
i += 1
if f[-1].isdigit() == False:
f += '' dic = {} key = ''
val = '' # H11He49N1O35B7N46Li20
for i in f:
if i.isdigit():
val += i
else:
if val == '':
key += i
else:
if key not in dic:
dic[key] = int(val)
else:
dic[key] += int(val)
key = i
val = '' if key not in dic:
dic[key] = int(val)
else:
dic[key] += int(val) keys = dic.keys()
keys.sort()
res = ''
#print dic
for i in keys:
res += i
if dic[i] > 1:
res += str(dic[i])
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. 在服务器上给tomcat指定jdk版本

    export JAVA_HOME=/usr/local/jdk1.8 --路径是:Jdk8所在的目录 export CATALINA_OPTS="-Djava.awt.headless=tr ...

  2. IDEA设置Ctrl+滚轮调整字体大小(转载)

    按Ctrl+Shift+A,出现搜索框 输入mouse: 点击打开这个设置:勾选 点击ok,之后就可以通过Ctrl+滚轮 调整字体大小了. 转载自:http://www.cnblogs.com/LUA ...

  3. 测开之路六十三:UI测试平台之视图层

    实现效果,在页面时配置 后台执行 蓝图结构 视图代码 from flask import jsonifyfrom flask import requestfrom flask import Bluep ...

  4. postgresql中实现按周统计详解

    SELECT EXTRACT(DOW FROM CURRENT_DATE);   执行结果如下. 这个SQL语句的意思就是计算当前日期是一周中的第几天. EXTRACT(DOW FROM CURREN ...

  5. 快速测试端口的连通性(HTTP/HTTPS)

    ping 仅限 80 端口,命令中无法指定端口: C:\Users\Administrator>ping kikakika.com 遗失对主机的连接. 正在 Ping kikakika.com ...

  6. Altium Designer chapter6总结

    绘制PCB中需要注意的如下: (1)网络表的载入:网络表是原理图与PCB之间的桥梁,而AD实现了真正的双向同步设计.在装入网表之前需要先添加相应的封装库. (2)元件的布局:一般采用手工布局:按照模块 ...

  7. stl vector创建二维数组

    vector<vector<); for (auto it = v.begin(); it != v.end(); it++) { ; (*it).reserve();//预留空间为5,但 ...

  8. PTA 1121 Damn Single

    题目链接:1121 Damn Single (25 分) "Damn Single (单身狗)" is the Chinese nickname for someone who i ...

  9. jQuery基础--插件

    1. 插件 1.1. 常用插件 插件:jquery不可能包含所有的功能,我们可以通过插件扩展jquery的功能. jQuery有着丰富的插件,使用这些插件能给jQuery提供一些额外的功能. 1.1. ...

  10. opencv部署服务器报错

    报错内容: ImportError: libSM.so.6: cannot open shared object file: No such file or directory 解决办法: sudo ...