I was doing a leetcode problem and I got a String index out of range: 0 exception for the below code:
public boolean isInterleave(String s1, String s2, String s3) {
int n = 0;
int m = 0;
if (s1.charAt(0) == s3.charAt(0)) {
n++;
for (int j = 1; j < s1.length(); j++) {
if (s1.charAt(j) == s3.charAt(j)) {
n++;
} else {
break;
}
}
for (int j = 0; j < s2.length(); j++) {
if (s2.charAt(j) == s3.charAt(j + n)) {
m++;
} else {
break;
}
}
}
if (n > 0) {
System.out.println(n);
} else {
System.out.println(m);
}
}
I tried to count how many characters of two strings are the same for a string like in the problem of interleaving String question and expected to print 2,2 for the
input s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
Te why, is because an empty string does not have a char at position 0, but you just don't need that first if.
The first for loop will not enter if the string
s1is empty but the second will.You could add a
ifbefore that for checking for emptyness, but I don't know what you should return in that case, something like this:I'm not saying this is what you should do to resolve your problem, just how to avoid the error you are having and as a form of exemplifying why you are having it.