//左到右遇到元素 数量 左括号 入栈
//遇到右括号 获取(基团/聚合)数量 出栈增加括号内元素的数量 然后再入栈
public static string Parse(string expression)
{
var stack = new Stack<string>();
var index = 0;
while (index < expression.Length)
{
if (char.IsLetter(expression[index]))
{
var e = GetNextElement(expression, index);
stack.Push(e);
index += e.Length;
if (index < expression.Length && char.IsNumber(expression[index]))
{
var n = GetNextNumber(expression, index);
stack.Push(n);
index += n.Length;
}
else
{
stack.Push("1");
}
}
else if (expression[index] == '[' || expression[index] == '(')
{
stack.Push(expression[index].ToString());
index++;
}
else
{
var c = 1;
if (index + 1 < expression.Length && char.IsNumber(expression[index + 1]))
{
var n = GetNextNumber(expression, index + 1);
index += n.Length + 1;
c = int.Parse(n);
}
else
{
index++;
}
var st = new Stack<string>();
while (stack.Peek() != "[" && stack.Peek() != "(")
{
var e = stack.Pop();
if (int.TryParse(e, out var t))
{
st.Push((t * c).ToString());
}
else
{
st.Push(e);
}
}
stack.Pop();
while (st.Count > 0)
{
stack.Push(st.Pop());
}
}
}
var dic = new Dictionary<string, int>();
while (stack.Count > 0)
{
var c = int.Parse(stack.Pop());
var e = stack.Pop();
if (dic.TryGetValue(e, out var t))
{
dic[e] = t + c;
}
else
{
dic[e] = c;
}
}
var es = dic.Keys.OrderBy(k => k);
var re = new StringBuilder();
foreach (var e in es)
{
re.Append($"{e}{dic[e]}");
}
return re.ToString();
}
public static string GetNextElement(string txt, int startIndex)
{
var len = 1;
while (startIndex + len < txt.Length && char.IsLower(txt[startIndex + len]))
{
len++;
}
return txt.Substring(startIndex, len);
}
public static string GetNextNumber(string txt, int startIndex)
{
var len = 1;
while (startIndex + len < txt.Length && char.IsNumber(txt[startIndex + len]))
{
len++;
}
return txt.Substring(startIndex, len);
}