栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用递归查找字符串中的字符

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用递归查找字符串中的字符

您的尝试很好,但是还不够。这是基于您的正确实现:

public static int indexOf(char ch, String str) {    // Returns the index of the of the character ch    if (str == null || str.equals("")) {        // base case: no more string to search; return -1        return -1;    } else if (ch == str.charAt(0)) {        // base case: ch is at the beginning of str; return 0        return 0;     }    // recursive step    int subIndex = indexOf(ch, str.substring(1));    return subIndex == -1 ? -1 : 1 + subIndex;}

您的尝试存在两个问题:

在这一

else if
部分中,您已经找到了角色,因此正确的做法是停止递归,但您仍在继续。

在最后一个return语句中,您需要在递归调用中加1(如果最终找到了该字符),作为累加总索引号的一种方式。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/455144.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号