题目如下:

解题思路:我用的是递归的方法,每次找出与第一个')'匹配的'('计算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. redirect thread aborted

    Why Response.Redirect causes System.Threading.ThreadAbortException? The correct pattern is to call t ...

  2. JPEG 存储分割后的图象会产生锯齿

    分割后的图象如果保存为 JPG 格式,物体边界会产生锯齿状的很暗的像素. 如下图所示. 这会给后续处理带了噪声, 因此,保存分割后的图象最好用无损压缩格式,如 bmp, png 等.

  3. 127、TensorFlow 计算图执行(二)

    import tensorflow as tf # Define a placeholder that expects a vector of three floating-point values ...

  4. ajax总结及案例

    一.实验简介 目的:检验输入登录名在数据库中是否存在,如果存在,当鼠标移出登录名框后,会提示用户名已存在,并且鼠标指针自动回到登录名框内. 操作步骤: 1.获取登录名的值 2.根据获取的登录名,组织查 ...

  5. Linux 初始化系统(init)- systemd

    wikipedia 浅析 Linux 初始化 init 系统 systemd 中文手册 fedoraproject - systemd 1. Systemd 简介 Systemd 是 Linux 系统 ...

  6. 16/8/23-jQuery完全图解scrollLeft,scrollWidth,clientWidth,offsetWidth 获取相对途径,滚动图片

    引用地址:http://www.cnblogs.com/mguo/archive/2013/03/19/2969657.html scrollLeft:设置或获取位于对象左边界和窗口中目前可见内容的最 ...

  7. spring事务——try{...}catch{...}中事务不回滚的几种处理方式(转载)

    转载自   spring事务——try{...}catch{...}中事务不回滚的几种处理方式   当希望在某个方法中添加事务时,我们常常在方法头上添加@Transactional注解 @Respon ...

  8. JavaScript高级程序设计(第3版) 第三章 (基本概念)

    3.1 语法 1.不以数字开头的数字,字母,下划线,美元符号 2.注释:html <!-- --> css/**/ js单行// 多行/**/ 3.ES5 引入了严格模式(strict m ...

  9. 利用多态,简易实现电脑usb连接设备案例

    package cn.learn.Practice03; public interface UsbInterface { void open(); //打开usb void close(); //关闭 ...

  10. Mysql 实现基于binlog的主从同步

    工作原理 1.主节点必须启用二进制日志,记录任何修改了数据库数据的事件.2.从节点开启一个线程(I/O Thread)把自己扮演成 mysql 的客户端,通过 mysql 协议,请求主节点的二进制日志 ...