如何仅用for循环与简单数组重构变位词生成代码?
Refactored Anagram Generator (Using Only Basic Loops & Arrays)
Got it, let's refactor your anagram code to stick strictly to basic for loops and arrays—ditching HashMap, StringBuilder, and other higher-level utilities while keeping the core functionality intact: preserving non-letter characters in their original positions and reversing the letter portions of each word.
Here's the fully refactored code:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Anagram { public static void main(String[] args) throws IOException { Anagram anagram = new Anagram(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { System.out.println("Enter word or phrase: "); String userText = reader.readLine(); String resultAnagram = anagram.makeAnagram(userText); System.out.println("Result of Anagram : " + resultAnagram); } } /** * Generates an anagram where non-letter characters stay in their original positions * @param text Input string from the user * @return Processed anagram string */ public String makeAnagram(String text) { String[] words = text.split(" "); char[] resultChars = new char[text.length()]; int resultIndex = 0; for (int i = 0; i < words.length; i++) { char[] wordChars = words[i].toCharArray(); int wordLength = wordChars.length; // Track non-letter positions and characters with parallel arrays (no HashMap) int[] nonLetterIndices = new int[wordLength]; char[] nonLetterChars = new char[wordLength]; int nonLetterCount = 0; // Collect only the letters to reverse later char[] letters = new char[wordLength]; int letterCount = 0; // Split the word into letters and non-letters for (int j = 0; j < wordLength; j++) { char c = wordChars[j]; if (isLetter(c)) { letters[letterCount++] = c; } else { nonLetterIndices[nonLetterCount] = j; nonLetterChars[nonLetterCount] = c; nonLetterCount++; } } // Reverse the collected letters using a basic loop reverseCharArray(letters, letterCount); // Build the processed word by merging reversed letters and original non-letters char[] processedWord = new char[wordLength]; int letterPtr = 0; int nonLetterPtr = 0; for (int j = 0; j < wordLength; j++) { // Check if current position is a non-letter spot boolean isNonLetterPosition = false; for (int k = 0; k < nonLetterCount; k++) { if (nonLetterIndices[k] == j) { processedWord[j] = nonLetterChars[nonLetterPtr++]; isNonLetterPosition = true; break; } } if (!isNonLetterPosition) { processedWord[j] = letters[letterPtr++]; } } // Copy the processed word into the final result array System.arraycopy(processedWord, 0, resultChars, resultIndex, wordLength); resultIndex += wordLength; // Add a space between words (except after the last word) if (i != words.length - 1) { resultChars[resultIndex++] = ' '; } } return new String(resultChars); } /** * Checks if a character is an English letter (A-Z, a-z) * @param c Character to check * @return True if it's a letter, false otherwise */ private boolean isLetter(char c) { return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'); } /** * Reverses the first `count` elements of a char array using basic loops * @param arr Array to reverse * @param count Number of elements to reverse (ignores empty slots) */ private void reverseCharArray(char[] arr, int count) { for (int i = 0; i < count / 2; i++) { char temp = arr[i]; arr[i] = arr[count - 1 - i]; arr[count - 1 - i] = temp; } } }
Key Refactoring Choices:
- Replaced HashMap with Parallel Arrays: Instead of using a map to track non-letter positions and characters, we use two simple arrays (
nonLetterIndicesandnonLetterChars) plus counters to track valid entries—no fancy collections needed. - Manual String Construction: We build the final result using a pre-sized char array (matching the input length) and
System.arraycopyto place processed words, avoiding StringBuilder entirely. - Explicit Letter Reversal: Instead of relying on
StringBuilder.reverse(), we implement our own reversal logic with a basic for loop that swaps elements from the start and end of the letter array. - Simplified Non-Letter Placement: Instead of deleting non-letters then reinserting them, we directly build the processed word by checking each position against our non-letter index array—this avoids tricky index offset bugs from the original code.
- Cleaner Readability: Extracted the letter-checking logic into a dedicated
isLettermethod, fixed the typo insaerchNonLetters, and added clear comments to explain each step.
This code behaves exactly like your original version: for input like Hello, World!, it returns olleH, dlroW! with all non-letter characters staying in their original spots.
内容的提问来源于stack exchange,提问作者lutsik
相关产品推荐
相关产品推荐

