题目如下:

解题思路:我用的是递归的方法,每次找出与第一个')'匹配的'('计算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. sql-hive笔试题整理 1 (学生表-成绩表-课程表-教师表)

    题记:一直在写各种sql查询语句,最长的有一百多行,自信什么需求都可以接,可......,想了想,可能一直在固定的场景下写,平时也是以满足实际需求为目的,竟不知道应试的题都是怎么出的,又应该怎么做.遂 ...

  2. sqlalchemy.exc.NoForeignKeysError:Can't find any foreign key relationships between

    这句话的意思是,两张表之间的外键找不到,首先看看外键设置正确了没,如果外键没问题,看看是不是_tablename_设置了没,就是再model中,定义类的时候,表格名称要_tablename_设置一下, ...

  3. MySQL innodb的组合索引各个列中的长度不能超过767,

    MySQL索引的索引长度问题   MySQL的每个单表中所创建的索引长度是有限制的,且对不同存储引擎下的表有不同的限制. 在MyISAM表中,创建组合索引时,创建的索引长度不能超过1000,注意这里索 ...

  4. 刚性方程 Stiff equation

    In mathematics, a stiff equation is a differential equation for which certain numerical methods for ...

  5. curl的一些常用命令

    在学习nodejs中get到了一项新的技能crul curl 可以给在命令行上面给node服务器发送一些信息,然后得到服务器返回而响应信息,在命令行中打印出来. 下面是我整理的一些常用的命令:

  6. STM32 在串口通信时运用MODBUS协议

    最近一个项目用到了MODBUS协议,就学习了一下,这里做一下记录以免后续忘记. 要用到MODBUS肯定要先知道是MOBUS协议,这里呢我们就又要先理解协议的含义了. 所谓的协议是什么?就是互相之间的约 ...

  7. LeetCode 129. Sum Root to Leaf Numbers 动态演示

    树的数值为[0, 9], 每一条从根到叶子的路径都构成一个整数,(根的数字为首位),求所有构成的所有整数的和 深度优先搜索,通过一个参数累加整数 class Solution { public: vo ...

  8. maven 配置阿里云中央仓库

    一.修改maven根目录下的conf文件夹中的setting.xml文件 <mirror> <id>alimaven</id> <name>aliyun ...

  9. mysql-时间格式

    SELECT DATE_FORMAT('2019-1-1 15:1:1.099','%Y-%m-%d %H:%i:%s.%f') -- 2019-01-01 15:01:01.099000 %a  缩 ...

  10. Server Tomcat v8.5 Server at localhost failed to start.

    问题描述:新建了一个项目,建立servlet文件然后改了下@WebServlet("floorButtonServlet")映射的路径,重启debug之后服务器启动失败. 在网上查 ...