题目如下:

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

代码如下:

class Solution(object):def recursive(self,formula):left = right = Nonefor i,v in enumerate(formula):if v == '(':left = ielif v == ')':right = ibreakif left == None and right == None:return formulalf = 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 -= 1breakif times != '':times = int(times)rf = formula[i+1:]if times == '':ts = parseelse:parseList = []val = ''val_num = ''parse += '#'for i in parse:#print parseListif 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 = ielif i.isdigit():if val != '':parseList.append(val)val = ''val_num += ielif 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 -> Mg1O2H2while i < len(f):if f[i].isupper() and f[i-1].isdigit() == False:f = f[:i] + '1' + f[i:]i = 1i += 1if f[-1].isdigit() == False:f += '1'dic = {}key = ''val = ''# H11He49N1O35B7N46Li20for i in f:if i.isdigit():val += ielse:if val == '':key += ielse:if key not in dic:dic[key] = int(val)else:dic[key] += int(val)key = ival = ''if key not in dic:dic[key] = int(val)else:dic[key] += int(val)keys = dic.keys()keys.sort()res = ''#print dicfor i in keys:res += iif dic[i] > 1:res += str(dic[i])return res

转载于:https://www.cnblogs.com/seyjs/p/9417866.html

【leetcode】726. Number of Atoms相关推荐

  1. 【Leetcode】Palindrome Number

    Determine whether an integer is a palindrome. Do this without extra space. 思路:若使用[Leetcode]Reverse I ...

  2. 【LeetCode】Palindrome Number(回文数)

    这道题是LeetCode里的第9道题. 题目说的: 判断一个整数是否是回文数.回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数. 示例 1: 输入: 121 输出: true 示例 2: ...

  3. 【LeetCode】191. Number of 1 Bits

    题目: Write a function that takes an unsigned integer and returns the number of '1' bits it has (also ...

  4. 【leetcode】Single Number (Medium) ☆

    题目: Given an array of integers, every element appears twice except for one. Find that single one. No ...

  5. leetcode【537】Complex Number Multiplication(复数相乘)

    写在最前面:一道很常规的字符串分割的题 leetcode[537]Complex Number Multiplication Given two strings representing two co ...

  6. 【leetcode】486. Predict the Winner

    题目如下: Given an array of scores that are non-negative integers. Player 1 picks one of the numbers fro ...

  7. 【LeetCode】Recursion(共11题)

    链接:https://leetcode.com/tag/recursion/ 247 Strobogrammatic Number II (2019年2月22日,谷歌tag) 给了一个 n,给出长度为 ...

  8. 【LeetCode】Minimum Depth of Binary Tree 二叉树的最小深度 java

    [LeetCode]Minimum Depth of Binary Tree Given a binary tree, find its minimum depth. The minimum dept ...

  9. 【LeetCode】第374题——猜数字大小(难度:简单)

    [LeetCode]第374题--猜数字大小(难度:简单) 题目描述 解题思路 代码详解 注意点 题目描述 猜数字游戏的规则如下: 每轮游戏,我都会从 1 到 n 随机选择一个数字. 请你猜选出的是哪 ...

最新文章

  1. mysql每一步花费时间_MySQL花费更多时间发送数据
  2. C++:不同数据类型作为参数传递和作为返回值的例子
  3. number 限制最长数字_阿博的Python之路Number数据类型详解
  4. 分形、混沌理论、集异璧之大成
  5. linux环境 下载Neo4j
  6. 卡尔曼滤波和互补滤波的区别
  7. Java题 细胞分裂
  8. tracker使用_如何使用Tracker查找钥匙,钱包,电话或其他任何东西
  9. Deep Learning Based Registration文章阅读(五)《Anatomy-guided Multimodal Registration by Learning Segment 》
  10. RadRails插件在 MyEclipse的安装(转http://wayfarer.blog.51cto.com/1300239/329290)
  11. 线程实例分析---线程的综合运用(精灵线程,多线程,中断,通信)【java养成】
  12. WebView的白屏检测与处理
  13. MySQL数据库快速入门
  14. MySQL性能优化(四):SQL优化
  15. Java是世界上最好的语言
  16. windows下查看lib,dll包含函数名
  17. 为什么Eureka比ZooKeeper更适合做服务发现?
  18. 大数据的七个核心应用价值
  19. 还没真正理解用户标签体系?看这篇就够了!
  20. 自定义内核启动后的Logo

热门文章

  1. 做Web应用程序时应该如何面向对象杂谈
  2. 深度学习的最新研究进展(三)
  3. liunx trac 插件使用之GanttCalendarPlugin
  4. Pytorch在colab和kaggle中使用TensorBoard/TensorboardX可视化
  5. [Android] TabLayout设置下划线(Indicator)宽度
  6. http响应状态码大全
  7. 已经连接到空闲例程的解决方法
  8. 美团搜索推荐多业务商品排序探索与实践
  9. shapenet各类数据(转载)
  10. 软件测试第一部分——初步概念与过程