Problem · String
Chemical Formula Weight
Learn this problemProblem statement
You are given a flat chemical formula, an array of distinct element symbols elements, and a parallel array weights. The weight of elements[i] is weights[i].
Each formula term is an uppercase letter followed by zero or more lowercase letters, then an optional positive decimal count. An omitted count means 1. Terms may repeat, and the formula contains no parentheses. Every symbol in the formula appears in elements.
Return the sum of each element's weight multiplied by its count as a 64-bit integer.
Function
formulaWeight(formula: String, elements: String[], weights: int[]) → longExamples
Example 1
formula = "CH4"elements = ["C","H"]weights = [12,1]return = 16C contributes 12 and four H atoms contribute 4.
Example 2
formula = "H2O"elements = ["H","O"]weights = [1,2]return = 4The supplied weights give 2 × 1 + 1 × 2 = 4.
Example 3
formula = "Na2Cl"elements = ["Na","Cl"]weights = [23,35]return = 81The multi-letter symbols contribute 2 × 23 + 35 = 81.
Constraints
1 <= formula.length <= 50001 <= elements.length == weights.length <= 100- Each symbol is one uppercase letter followed by at most two lowercase letters.
1 <= weights[i] <= 10^6- Every explicit count is between
1and999999. - The answer fits in a signed 64-bit integer.