Input validation


  • 0
    S
    public int romanToInt(String s) {
    	    if (s == null || s.length()==0) {
     return 0;
    	    }
    	    Map<Character, Integer> m = new HashMap<Character, Integer>();
    	    m.put('I', 1);
    	    m.put('V', 5);
    	    m.put('X', 10);
    	    m.put('L', 50);
    	    m.put('C', 100);
    	    m.put('D', 500);
    	    m.put('M', 1000);
    
    	    int length = s.length();
    	    int result = m.get(s.charAt(length - 1));
    	    for (int i = length - 2; i >= 0; i--) {
    	        if (m.get(s.charAt(i + 1)) <= m.get(s.charAt(i))) {
    	            result += m.get(s.charAt(i));
    	        } else {
    	            result -= m.get(s.charAt(i));
    	        }
    	    }
    	    return result;
    	}
    

    this is my code which was accepted by leetcode OJ, however, I realized there was no input validation for this method, what if input is "XIIV" which is actually a invalid roman numerals, but the code above can still work out result as 15. Anyone had this concern?


  • 0
    S
    public int romanToInt(String s) {
            Map<String, Integer> m = new HashMap<String, Integer>();
    	    m.put("I", 1);
    	    m.put("IV", 4);
    	    m.put("V", 5);
    	    m.put("IX", 9);
    	    m.put("X", 10);
    	    m.put("XL", 40);
    	    m.put("L", 50);
    	    m.put("XC", 90);
    	    m.put("C", 100);
    	    m.put("CD", 400);
    	    m.put("D", 500);
    	    m.put("CM", 900);
    	    m.put("M", 1000);
    	    int rst = 0;
    	    String[] roman = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
    	    for(int i = 0; i < roman.length; i++){
    	    	while(s.startsWith(roman[i])){
    	    		rst += m.get(roman[i]);
    	    		s = s.substring(roman[i].length());
    	    	}
    	    }
    	    if(s.length() != 0){
    	    	System.out.println("invalid input");
    	    	return 0;
    	    }
    	    else{
    	    	return rst;
    	    }
        }
    

    I might figure out with above code which pass the OJ, show me if I'm wrong.


  • 0
    K

    what about the "IIIII"?


Log in to reply
 

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