leetcode726. Number of Atoms

Posted seyjs

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode726. Number of Atoms相关的知识,希望对你有一定的参考价值。

题目如下:

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

 

以上是关于leetcode726. Number of Atoms的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] Largest Number At Least Twice of Others

[leetcode-748-Largest Number At Least Twice of Others]

726. Number of Atoms

[LeetCode] 747. Largest Number At Least Twice of Others_Easy

[LeetCode] 747. Largest Number At Least Twice of Others

LeetCode --- 1450. Number of Students Doing Homework at a Given Time 解题报告