string Java,选择subsequence
我的程序有一部分有问题
在下面的代码中,我们的字母表中有27个字母
目的是:对于外部for
的每一次重复,我们取text_generated
的最后n
个字符,对于字母表的每个字母,我们计算通过将字符添加到text_generated
的最后n
个字符中text_formatted
出现的次数;然后我们选择出现次数最多的字母,并将其附加到text_generated
。我得到的结果是:
***aaaaaaaaaaaaaaaaaaa
为什么
代码:
int index;
int[] occurrences = new int[27];
int count;
for(int a = 0; a < m; a++){ // m is the number of characters the user wants to add
for(int b = 0; b < 27; b++){
StringBuffer curr_word = new StringBuffer(text_generated.substring(text_generated.length()-n, text_generated.length()));
count = 0;
for(int c = 0; c <= text_formatted.length() -n-1;c++){
if(text_formatted.substring(c,c+n+1).equals(curr_word.append(array[b])))
count += 1;
}
occurrences[b] = count;
}
index = 0;
for(int d = 1; d < 27; d++){
if(occurrences[d] > occurrences[index])
index = d;
}
text_generated = text_generated.append(array[index]);
}
# 1 楼答案
您总是设置
index = 0
,所以选择数组[]中的第一个字母,它总是a
# 2 楼答案
结果是
***aaaaaaaaaaaaaaaaaaa
和这个循环指示引用数组中的每个项都是0。这意味着您的算法默认将
array[0]
附加到text_generated
字符串。这意味着问题出在这个街区可能的问题:
text_formatted.length() - n - 1
结果为负值李>if
的计算结果总是false
李>在这两种情况下,问题很可能与
n
和text_formatted
的值有关