【LeetCode 726】原子的数量(括号匹配问题+哈希计数)

题目

题目链接

题意概括

带括号问题的字符串处理问题
在这里插入图片描述

思路

  1. 看到括号,即借鉴后缀表达式类似的思路,使用栈进行括号处理
  2. 看数据范围1e3, 所以对于每个元素的计数,可以通过哈希,也可以直接排序后,相邻的相同元素数量加和即可。
    排序 O( n log n) 哈希 O(n)

code

#define formular formula
const int N=1e3+5;
class Solution {
public:
    struct ss{
        string name;int count;
        bool operator <(const ss b){return name<b.name;}
    }stack[N];int top;
    string countOfAtoms(string formula) {   top=0;
        for(int i=0;i<formula.length();i++){
            //括号处理
            if(formula[i]=='(' )
            	{stack[++top].name=formula.substr(i,1);continue;}
            if(formula[i]==')' ){
                //读数字
                int j=i+1,res=0;
                while(formula[j]<='9'&&formula[j]>='0') 
                	res*=10,res+=formular[j]-'0',j++;
                if(res==0) res++;
                i=j-1;//更新i
                //括号内的原子数都乘以这个倍数
                j=top;
                while(stack[j].name[0]!='('){
                    stack[j].count*=res;
                    j--;
                }
                //删除左括号
                stack[j].name=")";
                continue;
            } 
            //读名字
            int j=i+1;while(formular[j]<='z'&&formular[j]>='a') j++;
            stack[++top].name=formular.substr(i,j-i);
            //读数字
            stack[top].count=0;
            while(formular[j]<='9'&&formular[j]>='0') 
            	stack[top].count*=10,stack[top].count+=formular[j]-'0',j++;
            if(stack[top].count==0) stack[top].count++;
            i=j-1;//更新i值
        }
        //答案整理
        string ans="";  sort(stack+1,stack+top+1);
        for(int i=1;i<=top;i++)
        if(stack[i].name[0]=='('||stack[i].name[0]==')') continue;
        else if(stack[i].name==stack[i+1].name) 
        	stack[i+1].count+=stack[i].count;
        else if(stack[i].count>1) 
        	ans=ans+ stack[i].name + to_string(stack[i].count); 
        else ans=ans+ stack[i].name;
        return ans;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

GoesM

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值