★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-puyxcgig-me.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Given a chemical formula
(given as a string), return the count of each atom.git
An atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name.github
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.app
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:atom
Input: formula = "H2O" Output: "H2O" Explanation: The count of elements are {'H': 2, 'O': 1}.
Example 2:spa
Input: formula = "Mg(OH)2" Output: "H2MgO2" Explanation: The count of elements are {'H': 2, 'Mg': 1, 'O': 2}.
Example 3:code
Input: formula = "K4(ON(SO3)2)2" Output: "K4N2O14S4" Explanation: The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}.
Note:
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.給定一個化學式formula
(做爲字符串),返回每種原子的數量。
原子老是以一個大寫字母開始,接着跟隨0個或任意個小寫字母,表示原子的名字。
若是數量大於 1,原子後會跟着數字表示原子的數量。若是數量等於 1 則不會跟數字。例如,H2O 和 H2O2 是可行的,但 H1O2 這個表達是不可行的。
兩個化學式連在一塊兒是新的化學式。例如 H2O2He3Mg4 也是化學式。
一個括號中的化學式和數字(可選擇性添加)也是化學式。例如 (H2O2) 和 (H2O2)3 是化學式。
給定一個化學式,輸出全部原子的數量。格式爲:第一個(按字典序)原子的名子,跟着它的數量(若是數量大於 1),而後是第二個原子的名字(按字典序),跟着它的數量(若是數量大於 1),以此類推。
示例 1:
輸入: formula = "H2O" 輸出: "H2O" 解釋: 原子的數量是 {'H': 2, 'O': 1}。
示例 2:
輸入: formula = "Mg(OH)2" 輸出: "H2MgO2" 解釋: 原子的數量是 {'H': 2, 'Mg': 1, 'O': 2}。
示例 3:
輸入: formula = "K4(ON(SO3)2)2" 輸出: "K4N2O14S4" 解釋: 原子的數量是 {'K': 4, 'N': 2, 'O': 14, 'S': 4}。
注意:
formula
的長度在[1, 1000]
之間。formula
只包含字母、數字和圓括號,而且題目中給定的是合法的化學式。16ms
1 class Solution { 2 func countOfAtoms(_ formula: String) -> String { 3 var counter = [String: Int]() 4 5 var factors = [1] 6 var formula = Array(formula.characters) 7 var i = formula.count - 1 8 while i >= 0 { 9 if formula[i] == "(" { 10 factors.removeLast() 11 i -= 1 12 continue 13 } 14 15 // Digits 16 var f = 1 17 if formula[i].isDigit { 18 var j = i - 1 19 while formula[j].isDigit { j -= 1 } 20 let str = String(formula[j+1...i]) 21 f = Int(str)! 22 i = j 23 } 24 25 if formula[i] == ")" { 26 factors.append(f * factors.last!) 27 i -= 1 28 continue 29 } 30 31 // Atom 32 var j = i 33 while !formula[j].isUppercaseLetter {j -= 1} 34 let str = String(formula[j...i]) 35 counter[str, default: 0] += factors.last! * f 36 i = j - 1 37 } 38 39 var ret = "" 40 for (k, v) in counter.sorted(by: {$0.0 < $1.0}) { 41 ret += k + (v > 1 ? String(v) : "") 42 } 43 return ret 44 } 45 } 46 47 extension Character { 48 var isDigit : Bool { 49 return self >= "0" && self <= "9" 50 } 51 var isUppercaseLetter : Bool { 52 return self >= "A" && self <= "Z" 53 } 54 var isLowercaseLetter : Bool { 55 return self >= "a" && self <= "z" 56 } 57 }
1 class Solution { 2 func countOfAtoms(_ formula: String) -> String { 3 var formula = formula 4 var res:String = String() 5 var pos:Int = 0 6 var m:[String:Int] = parse(&formula, &pos) 7 var arr:[String] = [String](m.keys) 8 arr.sort() 9 for key in arr 10 { 11 res += key + (m[key,default:0] == 1 ? String() : String(m[key,default:0])) 12 } 13 return res 14 } 15 16 func parse(_ str:inout String,_ pos:inout Int) -> [String:Int] 17 { 18 var res:[String:Int] = [String:Int]() 19 while(pos < str.count) 20 { 21 if str[pos] == "(" 22 { 23 pos += 1 24 for (key,val) in parse(&str, &pos) 25 { 26 res[key,default:0] += val 27 } 28 } 29 else if str[pos] == ")" 30 { 31 pos += 1 32 var i:Int = pos 33 while(pos < str.count && isDigit(str[pos])) 34 { 35 pos += 1 36 } 37 var multiple = Int(str.subString(i, pos - i)) ?? 0 38 for (key,val) in res 39 { 40 res[key,default:0] *= multiple 41 } 42 return res 43 } 44 else 45 { 46 var i:Int = pos 47 pos += 1 48 while(pos < str.count && isLower(str[pos])) 49 { 50 pos += 1 51 } 52 var elem:String = str.subString(i, pos - i) 53 i = pos 54 while (pos < str.count && isDigit(str[pos])) 55 { 56 pos += 1 57 } 58 var cnt:String = str.subString(i, pos - i) 59 var number:Int = Int(cnt) ?? 0 60 var num:Int = cnt.isEmpty ? 1 : number 61 res[elem,default:0] += num 62 } 63 } 64 return res 65 } 66 67 func isDigit(_ char: Character) -> Bool { 68 return char >= "0" && char <= "9" 69 } 70 71 func isLower (_ char: Character) -> Bool 72 { 73 return char >= "a" && char <= "z" 74 } 75 } 76 77 extension String { 78 //subscript函數能夠檢索數組中的值 79 //直接按照索引方式截取指定索引的字符 80 subscript (_ i: Int) -> Character { 81 //讀取字符 82 get {return self[index(startIndex, offsetBy: i)]} 83 } 84 85 // 截取字符串:指定索引和字符數 86 // - begin: 開始截取處索引 87 // - count: 截取的字符數量 88 func subString(_ begin:Int,_ count:Int) -> String { 89 let start = self.index(self.startIndex, offsetBy: max(0, begin)) 90 let end = self.index(self.startIndex, offsetBy: min(self.count, begin + count)) 91 return String(self[start..<end]) 92 } 93 }