1

设 w 为长度为 n 的数组。用java编写一个分治算法,以确定3个连续相同字符出现的次数。下面是我写的算法。答案应该是 5,但它给了我一个 0。任何人都可以发现错误吗?给定 w = abrabbbcccccfhdddgfr 算法应该返回 5,因为它满足 3 个连续相同字符的 5 次出现:1 次 bbb,3 次 ccc e 1 次 ddd

public class Test {

    public static void main (String[] args){
        char[] w =     {'a','b','r','a','b','b','b','c','c','c','c',
                'c','f','h','d','d','d','g','f','r'};
        System.out.println(conta_triple_main(w));
    }

    public static int conta_triple_main(char[] w){
        if (w.length <= 2)
            return 0;
        else
            return conta_triple(w, 0, w.length-1);
    }

    public static int conta_triple(char[] w, int i, int f){
        int m,result;
        if( i >= f-1)
            return 0;
        else {
            m = (i + f)/2;
            int sx = conta_triple(w, i, m);
            int dx = conta_triple(w, m+1, f);
            result = sx + dx;
            if ((m >= w.length-1) && (w[m-1] == w[m]) && (w[m] == w[m+1]))
                result++;
            if ((m >= w.length-2) && (w[m] == w[m+1]) && (w[m+1] == w[m+2]))
                result++;
        }
        return result;
    }
}
4

2 回答 2

1

这个

    if ((m >= w.length-1) && (w[m-1] == w[m]) && (w[m] == w[m+1]))
        result++;

应该

    if ((m-1 >= i) && (m+1 <= f) && (w[m-1] == w[m]) && (w[m] == w[m+1]))
        result++;

下一个 if 语句类似。

最后,您需要检查(w[m] == w[m-1]) && (w[m] == w[m-2]).

于 2013-11-12T15:05:10.090 回答
0

这是我对你的课的介词:

public class Test {

public static void main(String[] args) {
    char[] w = {'a', 'b', 'r', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'c', 'c', 'f', 'h', 'd', 'd', 'd', 'g', 'f', 'r'};
    System.out.println(conta_triple_main(w));
}

public static int conta_triple_main(char[] w) {
    if (w.length <= 2) {
        return 0;
    } else {
        return conta_triple(w);
    }
}

public static int conta_triple(char[] w) {
    int result = 0;
    for (int i = 0; i < w.length - 2; i++) {
        char c = w[i];
        if (c == w[i + 1] && c == w[i + 2]) {
            result++;
        }
    }
    return result;
}
}
于 2013-11-12T15:21:15.327 回答