递归查找字符串中最长的单词
如何递归地找到字符串中最长的单词?
编辑
完毕,谢谢大家。这是修改后的代码。
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;
}
How to find the longest word in a string recursively?
EDIT
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
首先,我们假设句子字符串参数没有任何前导或尾随空格。您通过调用 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.
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.
提示 1:
将问题分解为两部分:
提示 2:
如果字符串中没有前导和尾随空格,则问题更容易解决初始输入字符串。
Hint 1:
Break the problem down into two parts:
Hint 2:
The problem is easier to solve if there are no leading and trailing spaces in the initial input string.
尝试使用分割字符串
Try splitting the string using