-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution726.cs
91 lines (81 loc) · 2.34 KB
/
Solution726.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
using System.Text;
using LeetCode.DataStructures;
namespace LeetCode.Solutions;
public class Solution726
{
/// <summary>
/// 726. Number of Atoms - Hard
/// <a href="https://leetcode.com/problems/number-of-atoms">See the problem</a>
/// </summary>
public string CountOfAtoms(string formula)
{
var i = formula.Length - 1;
var stack = new Stack<Dictionary<string, int>>();
stack.Push([]);
while (i >= 0)
{
if (formula[i] == ')')
{
stack.Push([]);
i--;
}
else if (formula[i] == '(')
{
var top = stack.Pop();
var multiplier = ParseNumber(formula, ref i);
foreach (var atom in top)
{
if (!stack.Peek().ContainsKey(atom.Key))
{
stack.Peek()[atom.Key] = 0;
}
stack.Peek()[atom.Key] += atom.Value * multiplier;
}
i--;
}
else
{
var atom = ParseAtom(formula, ref i);
var count = ParseNumber(formula, ref i);
if (!stack.Peek().ContainsKey(atom))
{
stack.Peek()[atom] = 0;
}
stack.Peek()[atom] += count;
}
}
var atomCounts = stack.Pop();
var sortedAtoms = new List<string>(atomCounts.Keys);
sortedAtoms.Sort();
var result = new StringBuilder();
foreach (var atom in sortedAtoms)
{
result.Append(atom);
if (atomCounts[atom] > 1)
{
result.Append(atomCounts[atom]);
}
}
return result.ToString();
}
private string ParseAtom(string formula, ref int i)
{
int start = i;
i--;
while (i >= 0 && char.IsLower(formula[i]))
{
i--;
}
return formula.Substring(i + 1, start - i);
}
private int ParseNumber(string formula, ref int i)
{
if (i < 0 || !char.IsDigit(formula[i])) return 1;
var start = i;
while (i >= 0 && char.IsDigit(formula[i]))
{
i--;
}
return int.Parse(formula.Substring(i + 1, start - i));
}
}