java O (n) clean code


  • 0
    U
    public class Solution {
    	public int romanToInt(String s) {
    		char[] c = s.toCharArray();
    		int prev = 0; 			// previous char
    		int sum = 0; 			// sum of current sequence
    		for (int i = 0; i < c.length; ++i) {
    			int curr = i;
    			if (helper(c[prev]) < helper(c[curr]))
    				sum -= 2 * helper(c[prev]);
    			sum += helper(c[i]);
    			prev = curr;
    		}
    
    		return sum;
    	}
        
    	private int helper(char c) {	// get Arabic numeral of a char
    		switch (c) {
    		case 'I':	return 1;
    		case 'V':	return 5;
    		case 'X':	return 10;
    		case 'L':	return 50;
    		case 'C':	return 100;
    		case 'D':	return 500;
    		case 'M':	return 1000;
    		default:	return -1;
    		}
    	}
    }
    

Log in to reply
 

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