zoukankan      html  css  js  c++  java
  • leetcode--Roman to Integer

    Given a roman numeral, convert it to an integer.

    Input is guaranteed to be within the range from 1 to 3999.

    public class Solution {
       /**
    	 * The algorithm is kind of greedy algorithm: cut the string into substrings such that
    	 * the length of each substring is as large as possible.<br> 
    	 * @param s -string, Roman expression of an integer
    	 * @return int
    	 * @author Averill Zheng
    	 * @version 2014-06-22
    	 * @since JDk 1.7
    	 */
    	public int romanToInt(String s) {
    		int sum = 0;
    		Map<String, Integer> roman2Int = new HashMap<String, Integer>();
    		int[] units = new int[]{1000,900,500,400,100,90,50,40,10,9,5,4,1};
            String[] romanNumeral = new String[]{"M","CM", "D", "CD", "C", "XC", "L",
            		"XL", "X", "IX", "V", "IV", "I"};
    		for(int i = 0; i < 13; ++i)
    			roman2Int.put(romanNumeral[i], units[i]);
    		int length = s.length();
    		int i = 0;
    		while(i < length){
    			if(i + 1 < length && (s.substring(i, i + 2).equals("CM") || s.substring(i, i + 2).equals("CD") ||
    					s.substring(i, i + 2).equals("XC") || s.substring(i, i + 2).equals("XL") ||
    					s.substring(i, i + 2).equals("IX") || s.substring(i, i + 2).equals("IV"))){
    				sum += roman2Int.get(s.substring(i, i + 2));
    				i += 2;
    			}			
    			else{
    				sum += roman2Int.get(s.substring(i, i + 1));
    				i += 1;
    			}
    		}
    		return sum; 
        }
    }
    

      

      

  • 相关阅读:
    几种常用的曲线
    0188. Best Time to Buy and Sell Stock IV (H)
    0074. Search a 2D Matrix (M)
    0189. Rotate Array (E)
    0148. Sort List (M)
    0859. Buddy Strings (E)
    0316. Remove Duplicate Letters (M)
    0452. Minimum Number of Arrows to Burst Balloons (M)
    0449. Serialize and Deserialize BST (M)
    0704. Binary Search (E)
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3803774.html
Copyright © 2011-2022 走看看