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

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

本文介绍了使用递归查找字符串中的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试查找字符串中字母的首次出现.例如,苹果中的p应该返回1.这就是我拥有的:

I am trying to find the first occurrence of a letter in a string. For example, p in apple should return 1. Here is what I have:

// Returns the index of the of the character ch
public static int indexOf(char ch, String str) {

    if (str == null || str.equals("")) {
        return -1;
    } else if(ch == str.charAt(0)) {
        return 1+ indexOf(ch, str.substring(1));
    }

    return indexOf(ch, str.substring(1));
}

它似乎没有返回正确的值.

It just doesn't seem to be returning the correct value.

推荐答案

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

Your attempt was good, but not quite there. Here is a correct implementation based off yours:

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;
}

您的尝试存在两个问题:

There were two problems with your attempt:

else if 部分中,您找到了该字符,因此正确的做法是停止递归,但是您正在继续递归.

In the else if part, you had found the character, so the right thing to do was stop the recursion, but you were continuing it.

在最后一个return语句中,您需要在递归调用中加1(如果最终找到了该字符),以累积总索引号.

In your last return statement, you needed to be adding 1 to the recursive call (if the character was eventually found), as a way of accumulating the total index number.

这篇关于使用递归查找字符串中的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 20:23