File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Question Link: https://leetcode.com/problems/roman-to-integer/
3
+ * Primary idea: Iterate through end to start, add or minus according to different situations
4
+ * Time Complexity: O(n), Space Complexity: O(n)
5
+ *
6
+ */
7
+
8
+ class RomanToInteger {
9
+ func romanToInt( s: String ) -> Int {
10
+ let dict = initDict ( )
11
+ let chars = [ Character] ( s. characters. reverse ( ) )
12
+ var res = 0
13
+
14
+ for i in 0 ..< chars. count {
15
+ guard let current = dict [ String ( chars [ i] ) ] else {
16
+ return res
17
+ }
18
+ if i > 0 && current < dict [ String ( chars [ i - 1 ] ) ] {
19
+ res -= current
20
+ } else {
21
+ res += current
22
+ }
23
+ }
24
+
25
+ return res
26
+ }
27
+
28
+ private func initDict( ) -> [ String : Int ] {
29
+ var dict = [ String: Int] ( )
30
+
31
+ dict [ " I " ] = 1
32
+ dict [ " V " ] = 5
33
+ dict [ " X " ] = 10
34
+ dict [ " L " ] = 50
35
+ dict [ " C " ] = 100
36
+ dict [ " D " ] = 500
37
+ dict [ " M " ] = 1000
38
+
39
+ return dict
40
+ }
41
+ }
You can’t perform that action at this time.
0 commit comments