首页 > 解决方案 > 如何从java中的递归函数返回特定字符串?

问题描述

方法的输入:

单词 = AbcDef

输入 = 3

w = AbcDef

以下代码显示输出:

fABCD

EFABCD

定义ABC

我只想返回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;
}

标签: javarecursionreturn

解决方案


请试试这个。希望它可以使用递归解决您的问题-> 如果您想旋转 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 "";
    }

推荐阅读