Why Im keep having this StringIndexOutOfBoundsException?


  • 0
    A

    This code works just fine in my Eclipse but when I try to submit it this StringIndexOutOfBoundsException just keep popin up.

    public class Solution {
        public String longestCommonPrefix(String[] strs) {
            int size = strs.length;
            int minStrLen = 0;
            String cmnStr = null;
            String crtStr = "";
            
            if(strs.length == 0){
                return "";
            }
            if(strs.length == 1){
            	return strs[0];
            }
            int[] lengthArray = new int[strs.length];
            for (int k = 0; k < strs.length; k++){
                lengthArray[k] = strs[k].length();
            }
            Arrays.sort(lengthArray);
            minStrLen = lengthArray[0];
            if(minStrLen == 0){
                return "";
            }
            
            for(int i = 0; i < size; i++){
                crtStr = strs[i];
                if (cmnStr == null){
                    cmnStr = crtStr;
                }
                for(int j = 0; j < minStrLen; j++){
                    if(crtStr.charAt(j) != cmnStr.charAt(j)){
                        cmnStr = cmnStr.substring(0,j);
    	                break;
                    }
                }
            }
            return cmnStr;
        }
    }
    

    Runtime Error Message: Line 31: java.lang.StringIndexOutOfBoundsException: String index out of range: 0
    Last executed input: []


  • 0
    C

    seem like your cmnStr is shorter and shorter. cmnStr = cmnStr.substring(0,j); this line , j is minStrlen length.


Log in to reply
 

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