交换角落的单词并翻转中间的字符

交换角落的单词并翻转中间的字符

In this article, we'll delve into a fascinating string manipulation problem that involves swapping corner words of a string and reversing the middle characters. This kind of problem is quite common in coding interviews, and it's a great way to enhance your understanding of string manipulation in Java.

Java提供了丰富的字符串操作工具。从基本的拼接和比较操作到更复杂的任务,如字符串反转和交换,Java的String API都可以处理。一个有趣的问题是交换字符串的首尾单词并反转中间字符。这个问题可以通过结合Java的内置String方法和一些手动逻辑来解决。

Problem Statement

给定一个字符串,我们需要交换第一个和最后一个单词,并且反转中间字符的顺序,保持字符串的第一个和最后一个字符不变。

方法

解决这个问题的策略很简单 −

  • Split the input string into words.

  • 交换第一个和最后一个单词。

  • Reverse the order of the middle characters while keeping the first and last characters of the string in their original positions.

  • 将单词重新组合成字符串。

Example

Below is a Java function that implements the approach described above −

import java.util.*; public class Main { public static String swapAndReverse(String input) { String[] words = input.split(" "); // Swap the first and last words String temp = words[0]; words[0] = words[words.length - 1]; words[words.length - 1] = temp; // Reverse the middle characters of the string, leaving the first and last characters intact for(int i = 0; i 2) { String middleCharacters = words[i].substring(1, words[i].length() - 1); String reversedMiddleCharacters = new StringBuilder(middleCharacters).reverse().toString(); words[i] = words[i].charAt(0) + reversedMiddleCharacters + words[i].charAt(words[i].length() - 1); } } // Join the words back into a string return String.join(" ", words); } public static void main(String[] args) { System.out.println(swapAndReverse("Hello world this is Java")); } } 登录后复制