开发者

Find the longest word in a string recursively

How to find the longest word in a string recursively?

EDIT

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

public static String longestWord(String sente开发者_如何学编程nce)
{
    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;
}


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.


Hint 1:

Break the problem down into two parts:

  • split the string into the first word and the rest of the string
  • find the longest of ...

Hint 2:

The problem is easier to solve if there are no leading and trailing spaces in the initial input string.


package com.kota.java;
import java.util.*;

class LongestWord{
    String str = "Ram is intelligent boy";
    String stringArray[] = str.split("\\s");

    public String compare(String st1, String st2) {
        if (st1.length() > st2.length()) {
            return st1;
        } else {
            return st2;
        }
    }

    LongestWord() {
        String word = "";
        for (int i = 0; i < stringArray.length; i++) {
            if (i == 0) {
                word = stringArray[0];
            }
            word = compare(word, stringArray[i]);
        }
        System.out.println("Longest word = " + word);
    }

    public static void main(String[] args) {
        new LongestWord();
    }
}
/**
 * Out put : Longest word = intelligent
 * 
 * */


Try splitting the string using

 String[] words = sentance.split(" ");
 String longest = null;
 String longestSize = 0;
 for (String str: words) {
    int size = str.length();

    if (longestSize < size) {
        longest = str;
        longestSize = size;
    }
 }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜