题目
题意概括
带括号问题的字符串处理问题
思路
- 看到括号,即借鉴后缀表达式类似的思路,使用栈进行括号处理
- 看数据范围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;
}
};