Skip to content

Prepare For Coder Interview – Denny

  • Basic
  • Medium
  • Hard
  • Architect
  • Life

Leetcode: Number of Atoms

Posted on January 18, 2018September 23, 2019 by braindenny

Number of Atoms



Similar Problems:

  • CheatSheet: Leetcode For Code Interview
  • Tag: #stack, #hashmap

Given a chemical formula (given as a string), return the count of each atom.

An atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name.

1 or more digits representing the count of that element may follow if the count is greater than 1. If the count is 1, no digits will follow. For example, H2O and H2O2 are possible, but H1O2 is impossible.

Two formulas concatenated together produce another formula. For example, H2O2He3Mg4 is also a formula.

A formula placed in parentheses, and a count (optionally added) is also a formula. For example, (H2O2) and (H2O2)3 are formulas.

Given a formula, output the count of all elements as a string in the following form: the first name (in sorted order), followed by its count (if that count is more than 1), followed by the second name (in sorted order), followed by its count (if that count is more than 1), and so on.

Example 1:
Input: 
formula = "H2O"
Output: "H2O"
Explanation: 
The count of elements are {'H': 2, 'O': 1}.
Example 2:
Input: 
formula = "Mg(OH)2"
Output: "H2MgO2"
Explanation: 
The count of elements are {'H': 2, 'Mg': 1, 'O': 2}.
Example 3:
Input: 
formula = "K4(ON(SO3)2)2"
Output: "K4N2O14S4"
Explanation: 
The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}.

Note:

  • All atom names consist of lowercase letters, except for the first character which is uppercase.
  • The length of formula will be in the range [1, 1000].
  • formula will only consist of letters, digits, and round parentheses, and is a valid formula as defined in the problem.

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.


// https://code.dennyzhang.com/number-of-atoms
// Basic Ideas: stack + hashmap
//
//   Convert characters into token
//     Mg(OH)2 -> Mg:1, (:1, O:1, H:1, ):2
//
//   If not ), keep pushing characters to stack
//   If ), find the repeat count. Keep poping, until find (
//         Push the new result back
//
// Complexity: Time O(n^2), Space O(n)
import ("sort"
        "strconv")
type MyNode struct {
    token string
    count int
}

func countOfAtoms(formula string) string {
    l := []MyNode{}
    j := 0
    for i:=0; i<len(formula); i++ {
        ch := formula[i]
        if ch >='a' && ch <= 'z' {
            l[j-1].token += string(ch)
        } else {
            // find count
            if formula[i] >='0' && formula[i] <='9' {
                count := "" 
                for i<len(formula) && formula[i] >='0' && formula[i] <='9' {
                    count += string(formula[i])
                    i++
                }
                // move back to avoid i++ in the loop
                i--
                c, _ := strconv.Atoi(count)
                l[j-1].count = c
            } else {
                l = append(l, MyNode{token:string(ch), count:1})
                j++
            }
        }
    }
    stack := []MyNode{}
    for _, node := range l {
        if node.token != ")" {
            stack = append(stack, node)
        } else {
            nodes := []MyNode{}
            for len(stack)>0 && stack[len(stack)-1].token != "(" {
                node_top := stack[len(stack)-1]
                node_top.count = node_top.count*node.count
                nodes = append(nodes, node_top)
                stack = stack[0:len(stack)-1]
            }
            // pop (
            stack = stack[0:len(stack)-1]
            for j, _ := range nodes {
                stack = append(stack, nodes[j])
            }
        }
    }
    m := map[string]int{}
    tokens := []string{}
    for _, node := range stack {
        m[node.token] += node.count
    }
    for token, _ := range m {
        tokens = append(tokens, token)
    }
    sort.Strings(tokens)
    res := ""
    for _, token := range tokens {
        if m[token] == 1 {
            res += token
        } else {
            res += token+strconv.Itoa(m[token])
        }
    }
    return res
}
linkedin
github
slack

Post Views: 2
Posted in HardTagged #classic, #stack, hashmap

Post navigation

Leetcode: Factorial Trailing Zeroes
Leetcode: Generate Parentheses

Leave a Reply Cancel reply

Your email address will not be published.

Tags

#array #backtracking #bfs #binarytree #bitmanipulation #classic #codetemplate #combination #dfs #dynamicprogramming #game #graph #greedy #heap #inspiring #interval #linkedlist #manydetails #math #misc #palindrome #recursive #slidingwindow #stack #string #subarray #trie #twopointer #twosum baseconversion binarysearch editdistance hashmap knapsack monotone oodesign presum redo review rotatelist series sql topologicalsort treetraversal unionfind

Recent Posts

  • Leetcode: Palindrome Partitioning III
  • Leetcode: Biggest Single Number
  • Leetcode: Max Consecutive Ones II
  • Leetcode: Minimum Cost to Connect Sticks
  • Leetcode: Minimum Swaps to Group All 1’s Together

Recent Comments

    Archives

    Categories

    • Amusing
    • Basic
    • Easy
    • Hard
    • Life
    • Medium
    • Resource
    • Review
    • Series
    • Uncategorized
    Proudly powered by WordPress | Theme: petals by Aurorum.