【发布时间】: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