为有牺牲多壮志,敢教日月换新天。

[Swift]LeetCode726. 原子的数量 | Number of Atoms

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: https://www.cnblogs.com/strengthen/p/10515957.html 
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

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.

给定一个化学式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 }

Runtime: 48 ms
Memory Usage: 19.7 MB
 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 }

 

 

posted @ 2019-03-12 12:42  为敢技术  阅读(297)  评论(0编辑  收藏  举报