ac solution code


  • 0

    Solution1. time = O(n); space = O(1)

    KEYS: Roman digits are based on SUM from end to start, not multiplication!!

     1. HashMap: [Char: ValueInRoman]
     2.Base case: last char
     3. Sum: Iteration in n-2...0 (second last to start)
         1) if val[i] < val[i+1], res -= val[i]
         1) if val[i] >= val[i+1], res += val[i]
    

    e.g. "DCXXI" = 621

    func romanToInt(_ s: String) -> Int {
        guard s.count > 0 else { return 0 }
        
        let map: [Character: Int] = ["I": 1,                        // 1. map: [Char: ValueInRoman]
                                    "V": 5,
                                    "X": 10,
                                    "L": 50,
                                    "C": 100,
                                    "D": 500,
                                    "M": 1000]
        
        let chs = Array(s), n = chs.count
        var res = map[chs[n - 1]]!                                  // 2. Start from last: n-1
        
        for i in stride(from: n - 2, through: 0, by: -1) {          // 3. Loop in n-2...0: because we need to compare val[i], val[i+1]
            let curVal = map[chs[i]]!, rightVal = map[chs[i + 1]]!  // SUM: (Sign is the same as comparison result)
            if curVal < rightVal {                                  // 3-1. if val[i] < val[i+1], res -= val[i]
                res -= curVal
            } else {                                                // 3-2. 1) if val[i] >= val[i+1], res += val[i]
                res += curVal
            }
        }
        return res
    }
    

Log in to reply
 

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