From ad01e5bdc36440fa4632028d1642b438ec5e690b Mon Sep 17 00:00:00 2001 From: Yi Gu Date: Wed, 15 Jun 2016 20:58:37 -0700 Subject: [PATCH] [Math] add Solution to Roman to Integer --- Math/RomanToInteger.swift | 41 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Math/RomanToInteger.swift diff --git a/Math/RomanToInteger.swift b/Math/RomanToInteger.swift new file mode 100644 index 00000000..845edabe --- /dev/null +++ b/Math/RomanToInteger.swift @@ -0,0 +1,41 @@ +/** + * Question Link: https://leetcode.com/problems/roman-to-integer/ + * Primary idea: Iterate through end to start, add or minus according to different situations + * Time Complexity: O(n), Space Complexity: O(n) + * + */ + +class RomanToInteger { + func romanToInt(s: String) -> Int { + let dict = initDict() + let chars = [Character](s.characters.reverse()) + var res = 0 + + for i in 0 ..< chars.count { + guard let current = dict[String(chars[i])] else { + return res + } + if i > 0 && current < dict[String(chars[i - 1])] { + res -= current + } else { + res += current + } + } + + return res + } + + private func initDict() -> [String: Int] { + var dict = [String: Int]() + + dict["I"] = 1 + dict["V"] = 5 + dict["X"] = 10 + dict["L"] = 50 + dict["C"] = 100 + dict["D"] = 500 + dict["M"] = 1000 + + return dict + } +} \ No newline at end of file