以递归方式查找字符串中最长的单词 [英] Find the longest word in a string recursively

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

问题描述

如何递归找到字符串中最长的单词?

How to find the longest word in a string recursively?

完成后,谢谢大家。这是修改后的代码。

Finished, thanks everyone. Here's the revised code.

public static String longestWord(String sentence)
{
    String longest;

    int i = sentence.indexOf(' ');

    if (i == -1)
    {
        return sentence;
    }

    String first = sentence.substring(0,i);
    first = first.trim();
    String rest = sentence.substring(i);
    rest = rest.trim();

    longest = stringcompare(first,longestWord(rest));

    return longest;
}


推荐答案

首先让我们假设句子字符串参数没有任何前导或尾随空格。你通过调用trim()来做递归的情况,这是明智的。

First of all let's assume that the sentence string argument doesn't have any leading or trailing spaces. You are doing this for the recursive case by calling trim() which is sensible.

然后我们需要定义两种情况,基本情况和递归情况。

Then we need to define two cases, the base case and the recursive case.

基本情况是找不到空格,即传入的句子只是一个单词。在这种情况下,只需返回句子。

The base case is where a space isn't found, i.e. the sentence passed in is just one word. In this case simply return the sentence.

在递归的情况下,我们得到第一个单词,其余的就像你所做的那样。在句子的其余部分打电话给longestWord。然后简单地返回第一个单词中最长的单词以及递归调用返回的内容。

In the recursive case we get the first word and the rest as you have done. Call longestWord on the rest of sentence. Then simply return the longest of the first word and whatever was returned by your recursive call.

这篇关于以递归方式查找字符串中最长的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆