每日一题:726. 原子的数量(堆栈)

题目:

给定一个化学式formula(作为字符串),返回每种原子的数量。

原子总是以一个大写字母开始,接着跟随0个或任意个小写字母,表示原子的名字。

如果数量大于 1,原子后会跟着数字表示原子的数量。如果数量等于 1 则不会跟数字。例如,H2O 和 H2O2 是可行的,但 H1O2 这个表达是不可行的。

两个化学式连在一起是新的化学式。例如 H2O2He3Mg4 也是化学式。

一个括号中的化学式和数字(可选择性添加)也是化学式。例如 (H2O2) 和 (H2O2)3 是化学式。

给定一个化学式,输出所有原子的数量。格式为:第一个(按字典序)原子的名子,跟着它的数量(如果数量大于 1),然后是第二个原子的名字(按字典序),跟着它的数量(如果数量大于 1),以此类推。

示例 1:

输入: 
formula = "H2O"
输出: "H2O"
解释: 
原子的数量是 {'H': 2, 'O': 1}。
示例 2:

输入: 
formula = "Mg(OH)2"
输出: "H2MgO2"
解释: 
原子的数量是 {'H': 2, 'Mg': 1, 'O': 2}。
示例 3:

输入: 
formula = "K4(ON(SO3)2)2"
输出: "K4N2O14S4"
解释: 
原子的数量是 {'K': 4, 'N': 2, 'O': 14, 'S': 4}。
注意:

所有原子的第一个字母为大写,剩余字母都是小写。
formula的长度在[1, 1000]之间。
formula只包含字母、数字和圆括号,并且题目中给定的是合法的化学式。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/number-of-atoms
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路:

看到要处理字符串和括号就考虑到用堆栈来处理这个问题。可以用一个stack来存有原子和其数量的map。遍历公式时遇到括号的时候,再放一个map进stack用来存括号内的原子和数量,并在括号结束后将这个map的内容存储到上一个,也就是存储当前括号外内容的map。遍历完公式后对在stack最顶上的map进行排序并返回成一个字符串。

代码:

class Solution {
public:
    
    string countOfAtoms(string formula) {
        string res;
        int i=0;
        int n = formula.size();

        // function that find and seperate atoms string
        auto parseAtom=[&]()->string{
            string cur;
            cur += formula[i++];
            while (i<n && islower(formula[i]))
            {
                cur+=formula[i++];
            }
            return cur;
        };

        // find and seperate nums of atoms from formula
        auto parseNum=[&]()->int
        {
            if (i == n || !isdigit(formula[i]))
            {
                return 1;
            }
            int res=0;
            while (i < n && isdigit(formula[i]))
            {
                res = res*10+int(formula[i++]-'0');
            }

            return res;
        };


        stack<map<string, int>> atoms;
        atoms.push({});
        //iterate through formula
        while (i < n)
        {
            // if cur char is (, push a empty map into curStack
            if (formula[i] == '(')
            {
                atoms.push({});
                i++;
            }
            // if cur char is ), pop the top map from curStack and add its content to previous one
            else if (formula[i] == ')')
            {
                i++;
                int cur = parseNum();
                auto curStack = atoms.top();
                atoms.pop();
                for (auto& [atom, v]:curStack)
                {
                    atoms.top()[atom] += v*cur;
                }
            }
            else{
                // add current atoms and num into the top stack
                string curAtom = parseAtom();
                int curNum = parseNum();
                atoms.top()[curAtom] += curNum;

            }
        }
        // get the top stack, which store all info about the atoms and counts in the formula
        auto& atomNum = atoms.top();
        
        //sort the top maps
        vector<pair<string, int>> atomPairs;
        for (auto&[atom, count]:atomNum)
        {
            atomPairs.emplace_back(atom, count);
        }
        sort(atomPairs.begin(), atomPairs.end());

        // add atoms and nums into res
        for (auto &atomPair:atomPairs)
        {
            res += atomPair.first;
            if (atomPair.second > 1)
            {
                res += to_string(atomPair.second);
            }
        }
        return res;
    }
};

结果:

执行用时:4 ms, 在所有 C++ 提交中击败了53.95%的用户

内存消耗:7.5 MB, 在所有 C++ 提交中击败了14.42%的用户

参考:

leetcode官方题解

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值