以递归方式查找字符串中最长的单词

编程入门 行业动态 更新时间:2024-10-18 20:24:13
本文介绍了以递归方式查找字符串中最长的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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.

更多推荐

以递归方式查找字符串中最长的单词

本文发布于:2023-11-30 09:33:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649510.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:递归   字符串   单词   最长   方式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!