roman to integer

问题:将给定的罗马字符串转换为整数。

class Solution {
public:
	int romanToInt(string s) {
		if(s.size() == 0) return 0;
        int re = 0;
		//index 表示当前应该处理的元素。
		int index = 0;
		int len = s.size();
		//处理跟M有关的数
	    int thousand = s.find_first_of('M');
		if (-1 != thousand ){//find 
			if( thousand == 0){//it's "M****"
				//处理连续M,连续则累加。
				while(index < len && s[index] == 'M'){
					re += 1000;
					++index;
				}
				//出现不连续的M,则是900.
				thousand = s.find_last_of('M');
				if (thousand > index){
					re += 900;
					index = thousand + 1;
				}
				if(index == len) return re;
			}
			else{//M没在第一位,则表示的数是介于[900,1000)
				re += 900;
				index = thousand + 1;
			}
		}
		//处理跟D有关的数,[400,900)
		int five_hun = s.find_first_of('D');
		if ( -1 != five_hun){
			if(five_hun == index){// >= 500
				re += 500;
				index++;			
			}
			else{// it must be "CD"
				re += 400;
				index = five_hun + 1;
			}
		}
		//处理跟C有关的数[90, )
		int hun = s.find_first_of('C');
		if (hun >= index){
			if (hun == index){
				//C前面没有X,[100, )
				while (index < len && s[index] == 'C'){ 
					re += 100;
					++index;
				}
				hun = s.find_last_of('C');
				if (hun > index){
					re += 90;
					index = hun + 1;
				}
				if(index == len) return re;
			}
			else{//it must be "XC"
				re += 90;
				index = hun + 1;
			}
		}

		//handle 'L'
		int five_ten = s.find_first_of('L');
		if (five_ten >= index){
			if (five_ten == index){//"V***"
				re += 50;
				index++;
				if(index == len) return re;
			}
			else{//"XV"
				re += 40;
				index = five_ten + 1;
			}
		}

		//handle the X
		int ten = s.find_first_of('X');
		if (ten >= index){
			if (ten == index && s[index + 1] == 'C'){
				re += 90;
				index += 2;
			}
			else if (ten == index){
				while (index < len && s[index] == 'X'){
					re += 10; ++index;
				}
				ten = s.find_last_of('X');//"IX"
				if (ten > index){
					re += 9;
					index = ten + 1;
				}
				if(index == len) return re;
			}
			else {
				re += 9;
				index = ten + 1;
			}
		}

		//handle 'V'
		int five = s.find_first_of('V');
		if (five >= index){
			if(five == index){
				re += 5;
				index++;
			}
			else{
				re += 4;
				index = five + 1;
			}
		}

		int ge = s.find_first_of('I');
		if(index > len - 1) return re;

		if(ge < len - 1 && s[ge + 1] == 'X')
		{
			re += 9;
			return re;
		}
	    while (ge != -1 && ge <= len - 1)
	    { re += 1; ge++; }
		return re;
	}
};

花了一晚上的时间,写出如此代码,真真说不过去了,烂的一塌糊涂。

你可能感兴趣的:(LeetCode,Algorithm,String,Class,roman)