Could someone help me to improve my solution? It said time limit exceeded


  • 0

    public class Solution {
    public int romanToInt(String s) {
    int result = 0;
    int length = s.length();
    for(int i=0; i<length; i++){
    String digit = String.valueOf(s.charAt(i));
    switch(digit){
    case "M": result = result + 1000;
    break;
    case "D": result = result + 500;
    break;
    case "C": if(i+1<length){
    if(String.valueOf(s.charAt(i+1)).equals("M"))
    {
    result = result + 900;
    i = i + 1;
    }
    else if(String.valueOf(s.charAt(i+1)).equals("D"))
    {
    result = result + 400;
    i = i + 1;
    }
    else{
    result = result + 100;
    }
    }else{
    result = result + 100;
    }
    break;
    case "L": result = result + 50;
    break;
    case "X": if(i+1<length){
    if(String.valueOf(s.charAt(i+1)).equals("C"))
    {
    result = result + 90;
    i = i + 1;
    }
    else if(String.valueOf(s.charAt(i+1)).equals("L"))
    {
    result = result + 40;
    i = i + 1;
    }
    else{
    result = result + 10;
    }
    }else{
    result = result + 10;
    }
    break;
    case "V": result = result + 5;
    break;
    case "I": if(i+1<length){
    if(String.valueOf(s.charAt(i+1)).equals("X"))
    {
    result = result + 9;
    i = i + 1;
    }
    else if(String.valueOf(s.charAt(i+1)).equals("V"))
    {
    result = result + 4;
    i = i + 1;
    }
    else{
    result = result + 1;
    }
    }else{
    result = result + 1;
    }
    break;
    }
    }
    return result;
    }
    }


  • 0
    Y
    This post is deleted!

  • 0
    This post is deleted!

  • 0

    @yixuanwang.start I modified my code as you suggested, it worked well! Thank you!


Log in to reply
 

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