【问题标题】:Divide and Conquer Algorithm [char array]分而治之算法[char数组]
【发布时间】:2013-11-12 14:54:27
【问题描述】:

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

【问题讨论】:

  • -1 你有什么问题?您看到了哪些错误等?
  • @bblincoe, Anyone can spot the error 是我猜的问题......它只是缺少一个问号。他有输入,预期输出和实际输出+他解决问题的尝试=> +1!
  • 看起来像是调试器的工作。看看你有没有通过if 声明
  • 我现在正在检查contra_triple。 :)
  • 一方面,尝试将 if ((m >= 更改为 ((m

标签: java arrays algorithm char


【解决方案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]) &amp;&amp; (w[m] == w[m-2])

【讨论】:

    【解决方案2】:

    这是我对你的班级的介词​​:

    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-02-02
      • 1970-01-01
      • 2011-12-31
      • 2015-05-03
      • 2012-01-01
      • 2013-02-03
      • 2019-06-03
      • 2017-06-08
      • 1970-01-01
      相关资源
      最近更新 更多