Leetcode 13. Roman to Integer

Leetcode 13. Roman to Integer_第1张图片
方法1 :第12题的变种。从左往右遍历string,check当前char符合哪个罗马数字,check后叠加进最后的结果中。这题主要还是edge cases的处理,就比谁更细心了。时间复杂1,空间复杂1.

class Solution {
     
    public int romanToInt(String s) {
     
        int res = 0;
        int[] values = {
     1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};    
        String[] symbols = {
     "M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
        int len = s.length();
        int count = 0;
        for(int i = 0; i< len; ++i){
     
            char c = s.charAt(i);
            if((c == 'I' || c == 'X' || c == 'C') && i != len - 1){
     
                char ch = s.charAt(i+1);
                if(c == 'I'){
     
                    if(ch == 'X'){
      res = res + 9; i++;}
                    else if(ch == 'V') {
     res = res + 4; i++;}
                    else if(ch == 'I') {
     count += 2;i++;}
                    else{
     res = res + 1;}
                }else if(c == 'X'){
     
                    if(ch == 'C') {
     res = res + 90; i++;}
                    else if(ch == 'L') {
     res = res + 40; i++;}
                    else{
     res = res + 10;}
                }else{
     
                    if(ch == 'M') {
     res = res + 900; i++;}
                    else if(ch == 'D') {
     res = res + 400; i++;}
                    else{
     res = res + 100;}
                }
            }else{
     
                for(int j = 0; j < 13; ++j){
     
                    if(symbols[j].length() == 1 && symbols[j].charAt(0) == c){
     
                        res = res + values[j];
                        break;
                    }
                }
            }
        }
        return res + count;
    }
}

你可能感兴趣的:(Leetcode,math)