java - 将非递归方法更改为递归方法
问题描述
我有两种非递归方法,其中一种读取字符串中的总“e”字符,另一种检查 ArrayList 是否按字母顺序排列。
public static int counter( String str ) {
int k = 0;
for( int i = 0; i < str.length(); i++) {
if( str.charAt(i) == 'e' || str.charAt(i) == 'E' ) {
k++;
}
}
return k;
}
public static boolean isAlpha( ArrayList<String> words ) {
int n = 0;
if ( words.isEmpty() ) {
return false;
} else if ( words.size() == 1 ) {
return true;
}
while( n < (words.size() - 1) ){
int j = words.get(n).compareTo( words.get(n + 1));
if ( j > 0 ) {
return false;
}
n++;
}
return true;
}
递归方法的定义是方法调用自身。我相信我理解这个概念,但是很难实现或将其转换为递归方法。我怎样才能把这些方法变成递归的,在做的时候我应该怎么想?另外,这是我的另一种方法,它只打印出指定数字大小的数字。
public static void printN( int n, int step ) {
if ( step > Math.pow( 10, n - 1 ) - 1 ) {
if ( step < Math.pow( 10, n ) - 1 ) {
if ( step % 2 == 0 ) {
if ( condition( step )) {
System.out.print( step + " " );
}
}
}
}
if ( step >= Math.pow( 10, n ) ) {
return;
}
printN( n, step + 1 );
}
条件方法检查数字的第一个数字(从右边开始)是否大于第二个数字,并再次检查第二个数字是否大于第三个数字。这个检查过程一直持续到最后一位。是否可以仅使用“int n”的参数值编写 printN“方法”?加上只有一个参数值的递归方式的“计数器”方法?
解决方案
编写递归函数/方法时要考虑的最重要的事情是何时从该方法返回。
import java.util.List;
public class Main {
public static void main(String[] args) {
// Test
System.out.println(counter("He She They", 0));
System.out.println(isSortedAlphabatically(List.of("Hello", "World")));
System.out.println(isSortedAlphabatically(List.of("Good", "Hello", "World")));
System.out.println(isSortedAlphabatically(List.of("Morning", "Good", "World")));
System.out.println(isSortedAlphabatically(List.of("Good", "Bad", "Morning", "Evening", "Poor", "Rich")));
System.out.println(isSortedAlphabatically(List.of("Bad", "Evening", "Good", "Morning", "Poor", "Rich")));
System.out.println(isSortedAlphabatically(null));
System.out.println(isSortedAlphabatically(List.of()));
}
public static int counter(String str, int count) {
if (str.isEmpty()) {
return count;
}
if (str.charAt(0) == 'e' || str.charAt(0) == 'E') {
// Call the function recursively with the substring starting from index 1 and
// count + 1
return counter(str.substring(1), count + 1);
}
// Call the function recursively with the substring starting from index 1
return counter(str.substring(1), count);
}
public static boolean isSortedAlphabatically(List<String> words) {
if (words == null || words.isEmpty()) {
return false;
}
if (words.size() == 1) {
return true;
}
return words.get(0).compareTo(words.get(1)) > 0 ? false
: isSortedAlphabatically(words.subList(1, words.size()));
}
}
输出:
3
true
true
false
false
true
false
false
推荐阅读
- spring - 在服务中使用多个服务或多个存储库?
- python - Celery - Memory Leak (Memory doesn't get free even after worker completed the task)
- azure - 以“S-”开头的 Azure ID 不明确
- java - 使队列达到最终状态所需的最小交换次数,每个元素不超过 2 次交换
- python - 把列表变成字典
- powershell - 查找安装 exe 的参数列表
- r - 官员:如何插入原始宽度和高度的图片
- spring - 如何在 Spring 中修复“无法将此命令分派到 Redis 集群,因为键具有不同的插槽”
- java - 存在用户联合时密码策略不起作用
- ios - didReceiveRegistrationToken / didRegisterForRemoteNotificationsWithDeviceToken 函数不调用 iOS 13