Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/e820c14687e70bd0755fd649ca8ee5a6 to your computer and use it in GitHub Desktop.
Save jianminchen/e820c14687e70bd0755fd649ca8ee5a6 to your computer and use it in GitHub Desktop.
Leetcode 726 - number of atoms - first writing, it took me over 90 minutes. I felt that it is similar to flatten dictionary.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NumberOfAtomsStudyJava
{
/// <summary>
/// https://gist.github.com/jianminchen/853271cbe0945f2fc930e646cb343e9d
/// Highlights of code review
/// 1. remove global variable index, use ref index
/// 2. add comment line 124, add DFS child dictionary to its parent dictionary
/// 3. line 133, run into exception, and then change the code to dict[key] = value
/// 4. change the code to make base case clear, move base case to the first one
/// 5. line 80 - sort keys first
/// study java code and then write C# code
/// </summary>
class Program
{
static void Main(string[] args)
{
//RunTestcase1();
//RunTestcase2();
RunTestcase3();
}
/*
Input:
formula = "H2O"
Output: "H2O"
Explanation:
The count of elements are {'H': 2, 'O': 1}.
*/
public static void RunTestcase1()
{
var result = countOfAtoms("H20");
Debug.Assert(result.CompareTo("H20") == 0);
}
/*
Input:
formula = "Mg(OH)2"
Output: "H2MgO2"
Explanation:
The count of elements are {'H': 2, 'Mg': 1, 'O': 2}.
*/
public static void RunTestcase2()
{
var result = countOfAtoms("Mg(OH)2");
Debug.Assert(result.CompareTo("MGO2H2") == 0);
}
/*
Input:
formula = "K4(ON(SO3)2)2"
Output: "K4N2O14S4"
Explanation:
The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}.
*/
public static void RunTestcase3()
{
var result = countOfAtoms("K4(ON(SO3)2)2");
Debug.Assert(result.CompareTo("K4N2O14S4") == 0);
}
/// <summary>
/// code review Feb. 2, 2018
/// </summary>
/// <param name="formula"></param>
/// <returns></returns>
public static String countOfAtoms(String formula) {
var answer = new StringBuilder();
int index = 0;
var counts = countOfAtoms(formula.ToCharArray(), ref index);
// Sort keys first
foreach (String name in counts.Keys.OrderBy(name => name)) {
answer.Append(name);
int count = counts[name];
if (count > 1)
{
answer.Append("" + count);
}
}
return answer.ToString();
}
/// <summary>
/// code review Feb. 2, 2018
/// </summary>
/// <param name="f"></param>
/// <returns></returns>
private static Dictionary<string, int> countOfAtoms(char[] f, ref int index) {
var answer = new Dictionary<String, int>();
var length = f.Length;
while (index != length) {
var current = f[index];
var isOpenBracket = current == '(';
var isCloseBracket = current == ')';
var isNotBracket = !isOpenBracket && !isCloseBracket;
if (isNotBracket)
{
var name = getName(f, ref index);
var lookup = answer.ContainsKey(name) ? answer[name] : 0;
var nextValue = lookup + getCount(f, ref index);
answer.Add(name, nextValue);
}
else if (isOpenBracket)
{
++index;
var subproblem = countOfAtoms(f, ref index);
int count = getCount(f, ref index);
// add DFS child dictionary to dictionary itself
foreach (var entry in subproblem)
{
var key = entry.Key;
var value = entry.Value;
var lookup = answer.ContainsKey(key) ? answer[key] : 0;
var nextValue = lookup + value * count;
answer[key] = nextValue; // run time exception - answer.Add call
}
}
else if (isCloseBracket)
{
++index;
return answer;
}
}
return answer;
}
/// <summary>
/// code review Feb. 2, 2018
/// </summary>
/// <param name="f"></param>
/// <returns></returns>
private static String getName(char[] f, ref int index)
{
String name = "" + f[index++];
while (index < f.Length && f[index] >= 'a' && f[index] <= 'z')
{
name += f[index++];
}
return name;
}
/// <summary>
///
/// </summary>
/// <param name="f"></param>
/// <returns></returns>
private static int getCount(char[] f, ref int index)
{
int count = 0;
var length = f.Length;
while (index < length && f[index] >= '0' && f[index] <= '9')
{
count = count * 10 + (f[index] - '0');
++index;
}
return count == 0 ? 1 : count;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment