java - 如何从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;
}
解决方案
请试试这个。希望它可以使用递归解决您的问题-> 如果您想旋转 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 "";
}
推荐阅读
- reactjs - React Native -- “React 无法识别 DOM 元素上的 `enterKeyHint` 道具”
- java - 静态变量java - 数组列表中的所有对象都具有相同的名称?
- jquery - 在没有旧数据 jquery bootstrap5 的情况下重新加载相同的模态
- vue.js - 异步函数结果
- c - 使用 OpenMP 任务的带中断的并行 for 循环
- powershell - 如何从 Invoke-webrequest 内容结果中钻取数据?
- android - 任务 ':common:kaptDebugKotlin' 执行失败
- azure - Azure devops - 内部版本号与内部版本 ID
- html - xmlns:xlink="http://www.w3.org/1999/xlink" 还有功能吗?
- javascript - 每当我运行 npm install --force 时,我都会遇到此错误