='(':ifisinstance(stack[i],int):stack[i]=stack[i]*multiplier i-=1stack.pop(i)# Stat the numberofatomsforiinrange(0,len(stack),2):ifstack[i]instat:stat[stack[i]]+=stack[i+1]else:stat[stack[i]]=stack[i+1]stat=sorted(stat.items(),key=lambda item:item[0])result=''forkey,...
接下来再对分子式进行分割,得出每个atom的数量后排序即可。原理很简单,代码写得很乱,仅供参考。 代码如下: classSolution(object):defrecursive(self,formula): left= right =Nonefori,vinenumerate(formula):ifv =='(': left=ielifv ==')': right=ibreakifleft == Noneandright ==None:returnformula lf=fo...
Given aformula, returnthe count of all elements as a string in the following form: the first name (in sorted order), followed by its count (if that count is more than 1), followed by the second name (in sorted order), followed by its count (if that count is more than 1), and s...
All atom names consist of lowercase letters, except for the first character which is uppercase. The length of formula will be in the range [1, 1000]. formula will only consist of letters, digits, and round parentheses, and is a valid formula as defined in the problem. 就是直接解析字符串...
/** @lc app=leetcode id=726 lang=cpp** [726] Number of Atoms*/// @lc code=startclassSolution{public:stringatom(strings,int&pos){stringres;while(isalpha(s[pos])){if(res.empty()||islower(s[pos]))res+=s[pos++];elsebreak;}returnres;}intcount(strings,int&pos){intnum=0;while(isd...
香草**美人 上传 leetcode (getCount()和getName()函数)如果遇到(,就去递归求解,返回的是一个Map(这里用TreeMap,因为要按照字典序),Map的key就是原子,点赞(0) 踩踩(0) 反馈 所需:1 积分 电信网络下载 aggregator_2.12-0.0.49.jar 2024-11-29 08:16:01 积分:1 ...
原子的数量 jasonnk 81 2020.07.04发布于 天津 C++ 解题思路对解析过程划分状态,然后根据状态转移写程序代码class Solution { public: string countOfAtoms(string formula) { map<string, long> atomNumMap; parseString(formula, 0, formula.size()-1,atomNumMap, 1); string...
726. Number of Atoms 726. Number of Atoms 难度:h class Solution: def countOfAtoms(self, formula: str) -> str: dic = {} stack = [] cure = '' curn = '' times = 1 for c in formula[::-1]: if c.isdigit(): curn = c+curn...
classSolution{publicStringcountOfAtoms(Stringformula){Stack<TreeMap<String,Integer>>stack=newStack<>();//curMap对字符串进行遍历TreeMap<String,Integer>curMap=newTreeMap<>();intlen=formula.length();for(inti=0;i<len;){charc=formula.charAt(i);if(c=='('){stack.push(curMap);//新建map对括...
【leetcode】726. Number of Atoms 题目如下: 解题思路:我用的是递归的方法,每次找出与第一个')'匹配的'('计算atom的数量后去除括号,只到分子式中没有括号为止。例如 "K4(ON(SO3)2)2" -> "K4(ONS2O6)2" -> "K4O2N2S4O12"。接下来再对分子式进行分割,得出每个atom的数量后排序即可。原理很简单,...