【问题标题】:How I return specific string from recursive function in java?如何从java中的递归函数返回特定字符串?
【发布时间】:2021-04-24 13:30:09
【问题描述】:

方法输入:

word = AbcDef

输入 = 3

w = AbcDef

以下代码显示输出:

fAbcDe

efAbcD

DefAbc

我只想返回 DefAbc。 如何为 return 关键字进行编码。

public static String match2(String word,int input,String w)
{
    StringBuilder st = new StringBuilder();
    StringBuilder st1 = new StringBuilder();
    String str = "";
    int count = 0;
            st.append(word.charAt(i));
            
        for(int j = 0;j < i;j++)
        {
            st.append(word.charAt(j));
                  
        }
        
    
                
    if(input!=0)
    {
        str = st.toString();
        System.out.println(str);
        int input2 = input-1;
        match2(str,input2,w);
    }
    
    return null;
}

【问题讨论】:

  • 为什么在第一个循环中有一个中断?这样,第一个循环就不会被多次执行。
  • 输出正确,但我只想返回 DefAbc 。
  • @Shr_c 我想让您看到的是,您的实现没有意义 - 您可以完全删除第一个循环并返回只需将最后一个字符添加到您的 StringBuilder st。你的第二个循环也是如此 - 外部只执行一次。所以没有太多关于如何让你的实现返回一个特殊字符串的解释——如果你总是想返回 DefAbc 你根本不需要算法,你可以在第一行返回这个字符串。 :-) 另一方面,您可能会修复您的实现并解释是什么使预期的字符串“DefAbc”特别。

标签: java recursion return


【解决方案1】:

请试试这个。希望它可以使用递归解决您的问题-> 如果您想旋转 3 个字符,tillValue 应该是->3

   static String recurse(String word, int count, int tillValue) {
        if (count == tillValue) {
            return word;
        }

        String recurse = recurse(word, count + 1,tillValue);
        word = swap(recurse);

        return word;
    }

    private static String swap(String word) {
        if (word.length() > 0) {
            String c = word.substring(word.length() - 1);
            String dc = c + word.substring(0, word.length() - 1);
            System.out.println(dc);
            return dc;
        }
        return "";
    }

【讨论】:

  • 如果我想将结果发送到相同的方法。我该怎么做。
  • 然后你必须把 tillValue =1 并且你必须把这个递归函数放在一个你想要多少旋转的循环中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-25
  • 1970-01-01
  • 2022-01-06
  • 2012-09-19
  • 2014-11-15
  • 2015-05-27
  • 2011-06-05
相关资源
最近更新 更多