java解决常见递归问题

最基本的,斐波那契数列,阶乘(0,1的阶乘均为1)

返回字母"x"第一次出现的位置

使用递归编写一个函数,读取一个字符串,返回字母"x"第一次出现的位置。例如,字符串

"abcdefghijklmnopqrstuvwxyz"中"x"第一次出现在索引 23 处。为简单起见,假设字符

串一定至少有一个"x"

java 复制代码
public class FindFirstPos {
    public static void main(String[] args) {
        String info = "abcdefghijklmnopqrstuvwxyz";
        System.out.println(FindFirstCharPos(info, 'x'));
    }
    public static int FindFirstCharPos(String info, char c){
       if(info.charAt(0) == c){
           return 0;
       }
       else{
           return 1 + FindFirstCharPos(info.substring(1), c);
       }
    }
}

字符串数组长度求和

使用递归编写一个函数,读取一个字符串数组,返回所有字符串的字母数之和。

如果输入数组是"ab", "c", "def", "ghij",那么因为一共有 10 个字母,

所以函数应该返回 10

java 复制代码
public class StringSum2 {
    public static void main(String[] args) {
        String[] arr = {"ab", "c", "world","def", "ghij","hello"};
        System.out.println(sumStr(arr, arr.length-1));
    }
    public static int sumStr(String[] arr, int n){
        if(n == 0){
            return arr[n].length();
        }
        else{
            return arr[n].length() + sumStr(arr, n - 1);
        }
    }
}
java 复制代码
public class PathNum {
    public static void main(String[] args) {
        int[][] arr = new int[3][7];
        System.out.println(pathNum(arr, 0, 0));
    }
    public static int pathNum(int[][] arr, int i, int j) {
        if(i == arr.length - 1 || j == arr[0].length - 1){
            return 1;
        }
        else {
            return pathNum(arr, i + 1, j) + pathNum(arr, i, j + 1);
        }
    }
}

判断回文

java 复制代码
public class Huiwen {
    public static void main(String[] args) {
        String info = "abcczba";
        System.out.println(isHuiWen(info));
    }
    public static boolean isHuiWen(String info){
        if(info.length() == 1){
            return true;
        }
        else if(info.length() == 2){
            return info.charAt(0) == info.charAt(1);

        }
        else{
            return (info.charAt(0) == info.charAt(info.length() - 1)) && isHuiWen(info.substring(1,info.length()-1));
        }
    }
}
相关推荐
wuminyu2 小时前
JVM规范学习总结:解释器与JIT编译器如何处理JVM字节码
java·linux·c语言·jvm·c++
txxzjmzlh3 小时前
SpringBoot 配置⽂件
java·spring boot·spring
小徐不徐说3 小时前
序列化与反序列化:把 C++ 对象可靠地保存下来
开发语言·数据库·c++·php
ragnwang3 小时前
Notes: Python pybind11 import C++ module
开发语言·c++·python
Wang's Blog3 小时前
Java 项目实战: 交友项目 - 搜索附近的功能概述和分析
java·开发语言·交友
骑着蜗牛撵大象3273 小时前
大模型 Agent 的沙箱护栏:gVisor 隔离、出口白名单与审计闭环
java·开发语言·jvm·安全·agent沙箱·gvisor·microvm
独泪了无痕3 小时前
Hutool之LocalDateTimeUtil:让时间间隔操作如虎添翼
java
Dxy12393102164 小时前
JS DES 加密详解
开发语言·javascript·arcgis
充值内卷4 小时前
我给桌面加了个鱼缸:C++ 写后端,WebView2 里养一座 Three.js 小岛
开发语言·javascript·c++
云和数据.ChenGuang5 小时前
深入解析 Python 的 dir():从用法到 CPython 源码实现
开发语言·人工智能·python·langchain