码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode】726. Number of Atoms

时间:2018-08-20 19:45:40      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:val   return   ret   解题思路   bre   upper   self   isl   time   

题目如下:

技术分享图片

解题思路:我用的是递归的方法,每次找出与第一个‘)‘匹配的‘(‘计算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] + 1 + f[i:]
                i = 1
            i += 1
        if f[-1].isdigit() == False:
            f += 1

        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

标签:val   return   ret   解题思路   bre   upper   self   isl   time   

原文地址:https://www.cnblogs.com/seyjs/p/9417866.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!