【leetcode】726. 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
        

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

时间: 2024-12-20 00:28:01

【leetcode】726. Number of Atoms的相关文章

【LeetCode】Single Number (2 solutions)

Single Number Given an array of integers, every element appears twice except for one. Find that single one. Note:Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 解法一:用map记录每个元素的次数,返回次数为1的元素 cl

【LeetCode】Single Number

原文: Given an array of integers, every element appears twice except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 解答: 常规解法:先对数组进行排序,然后通过按顺序判断每相邻两个数是否相同即可

【LeetCode】Single Number I &amp; II

Single Number I : Given an array of integers, every element appears twice except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? Solution: 解法不少,贴一种: 1 cla

【LeetCode】Largest Number 解题报告

[题目] Given a list of non negative integers, arrange them such that they form the largest number. For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330. Note: The result may be very large, so you need to return a string instead of

【LeetCode】Valid Number 解题报告

[题目] Validate if a given string is numeric. Some examples: "0" => true " 0.1 " => true "abc" => false "1 a" => false "2e10" => true Note: It is intended for the problem statement to be ambig

【Leetcode】Guess Number Higher or Lower II

题目链接: 题目: We are playing the Guess Game. The game is as follows: I pick a number from 1 to n. You have to guess which number I picked. Every time you guess wrong, I'll tell you whether the number I picked is higher or lower. However, when you guess a

【Leetcode】Happy Number

题目链接:https://leetcode.com/problems/happy-number/ 题目: Write an algorithm to determine if a number is "happy". A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the sq

【Leetcode】Ugly Number

题目链接:https://leetcode.com/problems/ugly-number/ 题目: Write a program to check whether a given number is an ugly number. Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since i

【Leetcode】Ugly Number II

题目链接:https://leetcode.com/problems/ugly-number-ii/ 题目: Write a program to find the n-th ugly number. Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first