simple one pass solution using unordered_map and reverse iterator


  • 0
    F

    we can use reverse iterator to traverse the string and generate the number in just one pass, the code is

    unordered_map<char, int> ch_value = {{'I', 1}, {'V', 5}, {'X', 10}, {'L', 50},
    							{'C', 100}, {'D', 500}, {'M', 1000}};
    
    	if (s.empty())
    		return 0;
    
    	int num = 0;
    
    	for (auto it = s.rbegin(); it != s.rend(); ++it){
    		if (it != s.rbegin()){
    			if (ch_value[*it] < ch_value[*(it-1)])
    				num -= ch_value[*it];
    			else
    				num += ch_value[*it];
    		}
    		else{
    			num += ch_value[*it];
    		}
    	}
    
    	return num;
    }
    

Log in to reply
 

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