我编写了检查 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));
}
}
错误:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 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())
最佳答案
您的while
语句的条件是错误的。您永远不会更改 C
的值。而不是 while (C != null)
你应该使用 while c != C.length()
或类似的东西。
您的 A != null
和 B != null
语句也存在同样的问题,因为 charAt
不会删除任何字符!
此外,您需要在 if
子句中检查 Strings
的边界:
if (a < A.length() && A.charAt(a) == C.charAt(c))
此外,如果您的目标是提高效率,您应该在方法的开头添加此检查,然后删除最后的 if
语句:
if (A.length() + B.length() != C.length())
return false;
关于java - 检查给定字符串是否与其他两个字符串交错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17867942/