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

标签 java arrays algorithm char

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

最佳答案

这个

    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])

关于java - 分而治之算法 [字符数组],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19932424/

相关文章:

java - 无法添加依赖 : Failed to resolve: androidx. 生命周期 :lifecycle-extensions:2. 2.0-rc2

javascript - JS : Get IDs of objects in specific order

javascript - 使用 javascript 连接两个变量并查找数组值位置

algorithm - 通过一次更改、插入或删除一个字符将一个单词转换为另一个单词

javascript - 使用三 Angular 函数通过圆绘制等距平行线

java - HBase:什么是 NotServingRegionException?

java - SAXNotRecognizedException : Feature 'http://javax.xml.XMLConstants/feature/secure-processing' not recognized

java - 发生 Firebase 身份验证 FirebaseNetworkException : A network error (such as timeout, 中断连接或无法访问的主机)

arrays - 如何获取 D 中数组元素的引用?

algorithm - 对于整数 A>0、B>0、N>0,找到整数 x>0、y>0,使得 N-(Ax+By) 是最小的非负数