我有这个问题,我需要使用 stack/s 反转第一个单词和第三个单词并交换反转单词的位置

I have this problem that I need to Reverse the first word and the third word using a stack/s and swap the positions of the reversed words

进口java.util.Scanner; 导入 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();

        Stack<Character> stack = new Stack<>();

        for(int i = 0; i < str.length(); i++){
            stack.push(str.charAt(i));
        }

        System.out.println("Reverse:");

        while(!stack.empty()){
            System.out.print(stack.pop());
        }
    }
}

我所做的是把整个句子颠倒过来, 例如“输入字符串:这是新常态”,我的输出是“lamron wen eht si sihT”。

预期输出是什么: “输出:eht 是 sihT 新常态。”

Reverse the first word and the third word using a stack/s and swap the positions of the reversed words.

您需要处理 3 件事:

  1. 从输入中识别第一个词 line/string 并反转它
  2. 从输入中识别第 3 个词 line/string 并反转它
  3. 交换颠倒的第一个和第三个单词

按照您的逻辑,您正在使用堆栈反转整个输入字符串,而不用查找第一个或第三个单词。这就是您将整个输入以反向格式作为输出的原因。

您需要将输入字符串按 space 拆分以获得单词数组,仅反转该数组中的第 1 个和第 3 个单词,并仅交换这 2 个单词。最后,将所有单词(单词数组)与 space 连接起来以生成所需的输出。下面是解决它的方法之一(这里是 working sample 你的例子):

public class Main {
    public static void main (String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("Please Enter a string: ");
        
        // split input string in to words by space
        String[] words = in.nextLine().split(" ");
        
        // performing reverse operation if 3 words are in the input at minimum
        // else output is same as input
        if (words.length >= 3) {
            String rev1 = reverse(words[0]); // reverse word-1
            String rev3 = reverse(words[2]); // reverse word-3
            // swap word 1 and 3
            words[0] = rev3;
            words[2] = rev1;
        }

        System.out.println("Reverse: " + String.join(" ", words));
    }
    
    public static String reverse(String word) {
        if (word == null) {
            return word;
        }
        Stack<Character> stack = new Stack<>();
        for(int i = 0; i < word.length(); i++){
            stack.push(word.charAt(i));
        }
        StringBuilder sb = new StringBuilder();
        while(!stack.empty()){
            sb.append(stack.pop());
        }
        return sb.toString();
    }
}