为什么我只比较两个字符串的第 0 个索引时却显示 stringoutofbounds 异常?

问题描述 投票:0回答:1

我正在做 leetcode 问题,并且我得到了以下代码的 String index out of range: 0 异常:-

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);
    }
}

我尝试计算一个字符串的两个字符串有多少个字符相同,就像交错字符串问题中的问题一样,并期望打印 2,2 输入 s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"

java string indexoutofboundsexception
1个回答
0
投票

为什么,是因为空字符串在位置 0 处没有字符,但你只是不需要第一个 if 。

如果字符串

s1
为空,第一个 for 循环将不会进入,但第二个会进入。

您可以在其之前添加一个

if
来检查是否为空,但我不知道在这种情况下您应该返回什么,如下所示:

public boolean isInterleave(String s1, String s2, String s3) {
    if (s1.isEmpty() || s2.isEmpty() || s3.isEmpty() {
        return ...; //what's appropriate for this case
    }
... //your code.
}

我并不是说这是你应该做的来解决你的问题,只是说如何避免你所遇到的错误,并作为举例说明为什么你会遇到这个错误。

© www.soinside.com 2019 - 2024. All rights reserved.