【问题标题】:Recursive function in counting words [closed]计数单词的递归函数[关闭]
【发布时间】:2013-06-11 18:16:17
【问题描述】:

你好,有人可以给我看一个关于如何使用递归函数计算句子中单词的java代码吗?我有点难以理解递归,也许代码可以帮助我理解谢谢

【问题讨论】:

  • 您好,欢迎来到 StackOverflow,但这里的问题是为特定问题保留的,这不是代码编写服务。
  • 相信我。代码不会。
  • Haskell 是一种很好的程序语言,可以轻松学习递归,如果是递归你的问题,你可以看得更清楚
  • 感谢您的回答:)

标签: java recursion


【解决方案1】:

这是您所要求的工作示例:

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * Sample class to demonstrate recursion
 * @author vmarche
 */
public class WordCount {

    public static void main (String [] args) {

        // Infinite loop
        while (true) {

            System.out.println("Please enter a sentence:");
            BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));

            try {
                String input = keyboard.readLine();
                int count = countWords(input);
                System.out.println("Number of words: " + count);
            }

            catch (Exception e) {
                System.exit(0);
            }
        }
    }

    /**
     * Counts the words in a sentence recursively
     * @param sentence      The input sentence
     * @return              The number of words
     */
    public static int countWords (String sentence) {

        if (sentence.isEmpty())
        return 0;

        // Find the first index of a space
        int space = sentence.indexOf(" ");

        // If space exists, return count of sub-sentence
        if (space != -1)
            return 1 + countWords(sentence.substring(space + 1));
        // Else space does not exist, return 1
        else
            return 1;
    }
}

【讨论】:

  • 这正是我的想法!!但我不知道如何将它放入代码中谢谢
【解决方案2】:

对于递归函数来说,这是一个非常不寻常的用例,但基本思想是这样的:

def countWordsIn (sentence):
    if sentence.hasNoMoreWords():
        return 0
    return 1 + countWords (sentence.stripFirstWord())

你真正需要学习的是,递归涉及用更简单的情况来陈述你的问题(例如,一个句子中的字数是在没有第一个单词的情况下添加到该句子的字数上的),并且有一个终止条件(没有更多的单词)。

【讨论】:

    【解决方案3】:
    public class RecursionDemonstration{
        public static int numWords(String sentence)
        {
            int i = sentence.indexOf(' ');
            if (i == -1) return 1;                          //Space is not found
            return 1+numWords(sentence.substring(i+1));
        }
        public static void main(String[] args) {
            System.out.println(numWords("Hello this is a test"));
        }
    
    }
    

    这个概念是慢慢缩小问题的规模,直到它变得微不足道,你可以直接解决它。
    您所需要的只是一个基本案例以及问题与子问题之间的关系。
    (PS:我的代码不适用于空字符串或以空格结尾的句子。它可以很容易地修复,但为了简单起见,我没有这样做)。

    【讨论】:

    • 你能解释一下这是如何工作的,一个图表会更好
    • 一个句子的单词数为:1+(句子中的单词数不包括第一个单词)。这是一个递归定义。
    猜你喜欢
    • 2023-02-04
    • 2019-01-12
    • 2018-05-20
    • 2021-02-13
    • 2022-01-19
    • 2018-08-07
    • 2023-04-05
    • 2013-11-17
    • 1970-01-01
    相关资源
    最近更新 更多