13. Roman to Integer

class Solution {

    private array $codeTable = [
                'I' => 1,
                'V' => 5,
                'X' => 10,
                'L' => 50,
                'C' => 100,
                'D' => 500,
                'M' => 1000
            ];

    /**
     * @param String $s
     * @return Integer
     */
    function romanToInt($s) {
        $words = str_split($s);
        $length = count($words);
        if ($length === 1) {
            return $this->codeTable[$s];
        }
        $result = 0;
        $before = '';
        foreach($words as $key => $word){
            $result += $this->codeTable[$word];
            if ($before === 'I' && ($word === 'V' || $word === 'X')) {
                $result -= 2;
            } else if($before === 'X' && ($word === 'L' || $word === 'C')) {
                $result -= 20;
            } else if($before === 'C' && ($word === 'D' || $word === 'M')) {
                $result -= 200;
            }
            $before = $word;
        }

        return $result;
    }
}

Last updated