递归实现指定字符移至字符串末尾的技术求助
Hey there! I totally get that wrapping your head around recursion can feel tricky at first—let's work through this problem step by step to make it click.
First, Let's Fix Your Existing Code & Break Down the Recursive Idea
Your current code has a small error (str.indexOf(0) isn't how you grab the first character—you need str.charAt(0)), and it's missing the core recursive logic. Recursion works by splitting a big problem into smaller, identical subproblems: solve the small ones, then combine their results to answer the big question.
For this task, the core rules are simple:
- Base Case: If the string is empty or has no more instances of the target character, return the string as-is (you already started this part, great job!).
- Recursive Step: Look at the first character of the current string:
- If it's the target character: We want to move it to the end. So recursively process the rest of the string, then append this character to the result.
- If it's not the target character: Keep it at the front, then append the result of recursively processing the rest of the string.
Complete Recursive Implementation
Here's the full working code with comments explaining each part:
public static String chToLast(String str, char ch) { // Base case: no characters left to process, or no target chars remaining if (str.isEmpty() || str.indexOf(ch) == -1) { return str; } // Split the string into the first character and the rest of the string char firstChar = str.charAt(0); String remainingString = str.substring(1); if (firstChar == ch) { // Move this target char to the end: process the rest first, then add this char return chToLast(remainingString, ch) + firstChar; } else { // Keep this non-target char at the front: add it to the processed rest return firstChar + chToLast(remainingString, ch); } }
Let's Walk Through Your Example
Let's use your test case: input "Hello world!" and target 'l':
- First call:
firstChar = 'H'(not 'l'), so return"H" + chToLast("ello world!", 'l') - Next call:
firstChar = 'e'(not 'l'), return"e" + chToLast("llo world!", 'l') - Next call:
firstChar = 'l'(target), returnchToLast("lo world!", 'l') + "l" - This pattern continues until we process all characters. Eventually, all non-'l' characters are built up first, followed by every 'l' we encountered—resulting in
"Heo word!lll"as expected.
Quick Recursive Mindset Tip
Don't try to trace every single recursive call in your head all at once. Instead, focus on two things:
- What's the smallest version of the problem I can solve right away (the base case)?
- For a bigger problem, how can I shrink it into a smaller problem, then combine that smaller result with my current step?
内容的提问来源于stack exchange,提问作者Escaban

