Swift 3.0 Solution


  • 0
    D

    I mapped the string as an array and worked my way from the ending index to the front index. I used a currentChar and nextChar variable and handled oddball cases with a switch statement.

        func romanToInt(_ s: String) -> Int {
            
            var result: Int?
            
            let dictionary = ["I": 1,
                              "V": 5,
                              "X": 10,
                              "L": 50,
                              "C": 100,
                              "D": 500,
                              "M": 1000]
            
            var stringArray = s.characters.map({String($0)})
            
            var numberArray: [Int] = []
            
            var index: Int = stringArray.count - 1
            
            while index >= 0 {
                let currentChar: String = stringArray[index]
                var currentCharVal: Int = dictionary[currentChar]!
                
                if index < stringArray.endIndex - 1 {
                    let nextChar = stringArray[index + 1]
                    switch currentChar {
                    case "I" where nextChar == "V" || nextChar == "X":
                        currentCharVal = currentCharVal * -1
                    case "X" where nextChar == "L" || nextChar == "C":
                        currentCharVal = currentCharVal * -1
                    case "C" where nextChar == "D" || nextChar == "M":
                        currentCharVal = currentCharVal * -1
                    default:
                        break
                    }
                }
                
                numberArray.append(currentCharVal)
                
                index -= 1
            }
            
            
            result = numberArray.reduce(0, +)
            
            return result ?? -1
        }
    }```

Log in to reply
 

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