You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用栈实现字符串首单词与第三单词反转并交换位置?

Solution: Reverse and Swap First & Third Words

Your current code reverses the entire string, but we need to target specific words, reverse them, then swap their positions. Let's break down how to fix this:

Step-by-Step Approach

  1. Split the Input String: Break the input into individual words so we can work on specific positions.
  2. Reverse Target Words: Use a stack (as your original code does) to reverse the first and third words.
  3. Swap Reversed Words: Replace the first word with the reversed third word, and the third word with the reversed first word.
  4. Reconstruct the String: Join the modified words back into a single string for output.

Corrected Java Code

import java.util.Scanner;
import java.util.Stack;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("Please Enter a string: ");
        String str = in.nextLine();
        
        // Split the string into words (handles multiple spaces)
        String[] words = str.split("\\s+");
        
        // Check if there are at least 3 words to process
        if (words.length < 3) {
            System.out.println("Error: Input must have at least 3 words.");
            return;
        }
        
        // Reverse the first and third words using a stack
        String reversedFirst = reverseWord(words[0]);
        String reversedThird = reverseWord(words[2]);
        
        // Swap the reversed words in their positions
        words[0] = reversedThird;
        words[2] = reversedFirst;
        
        // Join the words back into a single string
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < words.length; i++) {
            result.append(words[i]);
            if (i != words.length - 1) {
                result.append(" ");
            }
        }
        
        // Print the final result
        System.out.println("Output: " + result.toString());
    }
    
    // Helper method to reverse a single word using a Stack
    private static String reverseWord(String word) {
        Stack<Character> stack = new Stack<>();
        // Push each character of the word onto the stack
        for (char c : word.toCharArray()) {
            stack.push(c);
        }
        
        // Pop characters from stack to build reversed word
        StringBuilder reversed = new StringBuilder();
        while (!stack.isEmpty()) {
            reversed.append(stack.pop());
        }
        
        return reversed.toString();
    }
}

How It Works

  • Splitting the String: split("\\s+") splits the input on one or more whitespace characters, so it handles cases where words are separated by multiple spaces.
  • Reverse Helper Method: The reverseWord method uses a stack to reverse individual words—this keeps the core logic from your original code but applies it to single words instead of the entire string.
  • Swapping Words: We replace the first element in the words array with the reversed third word, and vice versa.
  • Reconstructing the String: We use a StringBuilder to efficiently join the modified words back into a single string with proper spacing.

Example Test

Input: This is the new normal
Output: eht is sihT new normal

Which matches your expected output (the trailing dot in your example was likely a typo).

内容的提问来源于stack exchange,提问作者Thunderbirdfury 12

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 12:32:38