我编写了用于检查 S3 是否是 S1 和 S2 字符串交错的代码。
但是对于像 "AB" , "CD" -> "ACBD" 这样的简单字符串,它会失败
我错过了什么吗?
class InterleavedString {
// error
public static boolean isInterleaved (String A, String B, String C)
{
// Iterate through all characters of C.
int a = 0, b = 0, c = 0;
while (C != null)
{
// Match first character of C with first character of A,
// If matches them move A to next
if (A.charAt(a) == C.charAt(c))
a++;
// Else Match first character of C with first character of B,
// If matches them move B to next
else if (B.charAt(b) == C.charAt(c))
b++;
// If doesn't match with either A or B, then return false
else
return false;
// Move C to next for next iteration
c++;
}
// If A or B still have some characters, then length of C is smaller
// than sum of lengths of A and B, so return false
if (A != null || B != null)
return false;
return true;
}
public static void main(String [] args) {
String A = "AB", B = "CD", C = "ACBD";
System.out.println(isInterleaved(A, B, C));
}
}
错误 :
线程“主”java.lang.StringIndexOutOfBoundsException 中的异常:字符串索引超出范围:2 at java.lang.String.charAt(Unknown Source) at strings.InterleavedString.isInterleaved(InterleavedString.java:14) at strings.InterleavedString.main (InterleavedString.java:40)
编辑:
while (c != C.length())
.....
.....
if (a != A.length() || b != B.length())