检查给定的字符串是否是另外两个字符串的交错

时间:2013-07-25 20:16:52

标签: java string algorithm data-structures

我编写了代码,用于检查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));
    }
}

错误:

  

线程“main”中的异常java.lang.StringIndexOutOfBoundsException:   字符串索引超出范围:java.lang.String.charAt中的2(未知   来源)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())

3 个答案:

答案 0 :(得分:3)

while声明的条件错误。您永远不会更改C的值。您应该使用while (C != null)或类似的东西来代替c != C.length()

您的A != nullB != null语句也存在同样的问题,因为charAt不会删除任何字符!

此外,您需要检查Strings条款中if的范围:

if (a < A.length() && A.charAt(a) == C.charAt(c))

此外,如果您的目标是提高效率,则应在方法开头添加此检查,然后删除最后的if语句:

if (A.length() + B.length() != C.length())
    return false;

答案 1 :(得分:0)

这是错误的。尝试使用“XXY”,“XXZ”,“XXZXXY”..输出将为false

答案 2 :(得分:0)

boolean interleaving(String s1, String s2, String s3){
        char a[] = s1.toCharArray();
        char b[] = s2.toCharArray();
        char c[] = s3.toCharArray();

        if(a.length+b.length!=c.length){
            return false;
        }

        int i=0,j=0,k=0;

        while(k<=c.length-1){
           if(i<a.length && c[k]==a[i]){
               i++;
           }else if(j<b.length && c[k]==b[j]){
               j++;
           }else{
               return false;
           }
           k++;
        }

        return true;
    }
相关问题