简体   繁体   English

分而治之算法[字符数组]

[英]Divide and Conquer Algorithm [char array]

Let w be an array of length n. 令w为长度为n的数组。 Write a divide and conquer algorithm in java to determine the number of times 3 consecutive identical caracters appear. 用Java编写分而治之算法,以确定3个连续的相同角色出现的次数。 Below is the algorithm I've written. 以下是我编写的算法。 The answer should be 5 but it gives me a 0. Can anyone spot the error? 答案应该是5,但是给我0。有人可以发现错误吗? Given w = abrabbbcccccfhdddgfr the algorithm should return 5 because it meets five occurrences of 3 consecutive identical characters : 1 time bbb, 3 times ccc e 1 time ddd 给定w = abrabbbcccccfhdddgfr,该算法应返回5,因为它遇到5次出现了3个连续相同的字符: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;
    }
}

This 这个

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

should be 应该

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

Similar for the next if statement. 与下一个if语句相似。

Finally you need to check for (w[m] == w[m-1]) && (w[m] == w[m-2]) . 最后,您需要检查(w[m] == w[m-1]) && (w[m] == w[m-2])

Here is my preposition for Your class: 这是我为您上课的介词:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM