简体   繁体   中英

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

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.

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, ie 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM