1. 程式人生 > >letcode-13-roman to integer

letcode-13-roman to integer

python:

        sum=0
        d={'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
        for i in range(len(s)-1):
            if d[s[i]]<d[s[i+1]]:
                sum=sum-d.get(s[i])
            else:
                sum+=d.get(s[i])
        sum+=d[s[-1]]
        return sum

tips:

range倒序:range(len-1,-1,-1)#從len-1到0

java:

public int romanToInt(String s) {
       LinkedHashMap<String, Integer> roman = new LinkedHashMap< String,Integer>();		
		roman.put("I", 1);
		roman.put("V", 5);
		roman.put("X", 10);
		roman.put("L", 50);
		roman.put("C", 100);
		roman.put("D", 500);
		roman.put("M", 1000);
		List<String> index_s =new ArrayList<String> (roman.keySet());
		int sum=0;
		int b=0;
		int flag;
		for(int i=s.length()-1;i>=0;i--) {
			flag=0;
			int a=(int)index_s.indexOf(String.valueOf(s.charAt(i)));/*值,索引*/
			if(i-1>=0) {
				b=(int)index_s.indexOf(String.valueOf(s.charAt(i-1)));
				if(a==b+1) {
					sum+=4*Math.pow(10, b/2);
					i-=1;
					flag=1;
				}
				if(a==b+2) {
					sum+=9*Math.pow(10, b/2);
					i-=1;
					flag=1;
				}
			}			
			if(flag==0) {
					int c=roman.get(String.valueOf(s.charAt(i)));
					sum+=c;
				}
				
		}	
		return sum;
    }

tips:

 類似於dict的Map。HashMap(根據key的雜湊排序),TreeMap(根據key的值升序),LinkedMap(根據輸入順序)。

初始化:LinkedHashMap<String, Integer> roman = new LinkedHashMap< String,Integer>();         輸入:roman.put("I", 1);

鍵的set:.keySet()

鍵對應的值:   .get(key)

初始化arrayslist:List<String> index_s =new ArrayList<String> (roman.keySet());

list取索引:   .indexOf(value)

string取索引對應的值:  .charAt(index)

char->string:    String.valueOf(s.charAt(i))