我必须编写一个方法来返回给定字符串中的最小字符(使用 ASCII 序列)。示例 minChar("hello");应返回“e”。
目前我正在尝试运行 minChar("hello", 0)。我的想法是,它将从 h (h < ~) 开始,因此它会设置 c = h,然后调用 minChar("hello", 1),分配 c = e,依此类推,在最终返回 'e' 之前比较字母,因为这是最小值。我错过了什么?
public static char minChar(String x, int z){
char c = '~';
while(z < x.length()){
if(x.charAt(z) < c){
c = x.charAt(z);
}
minChar(x, z+1);
}
return c;
}
最佳答案
您没有使用 minChar()
返回的内容。使用它。
public static char minChar(String x, int z){
char c = '~';
if(z < x.length()){
if(x.charAt(z) < c){
c = x.charAt(z);
}
char candidate = minChar(x, z+1); // add assignment
if (candidate < c) c = candidate; // add update
}
return c;
}
关于java - 使用递归查找给定字符串中的最小字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35933257/