前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。
博客链接:mcf171的博客
——————————————————————————————
Given a roman numeral, convert it to an integer.Input is guaranteed to be within the range from 1 to 3999.
这个题目最简单直观的解法就是判断前缀。Your runtime beats 33.15% of java submissions.
public class Solution {
public int romanToInt(String s) {
int[] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };
String[] numerals = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };
int result = 0;
for (int i = 0; i < numerals.length; i++) {
boolean flag = true;
while(s.length()>0&&flag){
flag = false;
if(s.startsWith(numerals[i])){
s = s.substring(s.indexOf(numerals[i])+numerals[i].length());
result += values[i];
flag = true;
}
}
}
return result;
}
}