A Swift Solution


  • 1
    T
        let record:[Character:Int] = ["M": 1000, "D": 500, "C": 100, "L": 50, "X": 10, "V": 5, "I": 1]
        func romanToInt(s: String) -> Int {
            var index = s.endIndex.predecessor()
            var result:Int = 0
            var preCh = s[index]
            
            result += record[preCh]!
            
            if s.characters.count > 1 {
                while index.predecessor() != s.startIndex {
                    index = index.predecessor()
                    result += middleResult(s[index], preCh)
                    preCh = s[index]
                }
                result += middleResult(s[s.startIndex], preCh)
            }
    
            return result
        }
        
        func middleResult(p: Character, _ q: Character)->Int {
            if record[p]! < record[q]! {
                return record[p]! * -1
            }
            return record[p]!
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.