交換首尾單詞並反轉中間字元


在本文中,我們將深入探討一個關於字串操作的有趣問題,該問題涉及交換字串的首尾單詞並反轉中間字元。這種問題在編碼面試中非常常見,它是提高你對 Java 中字串操作理解的好方法。

Java 提供了一套豐富的字串操作工具。從基本操作(如連線和比較)到更復雜的任務(如字串反轉和交換),Java 的 String API 都能勝任。一個有趣的問題是交換字串的首尾單詞並反轉中間字元。這個問題可以使用 Java 內建的 String 方法和一些手動邏輯相結合來解決。

問題陳述

給定一個字串,我們需要交換第一個和最後一個單詞,並反轉中間字元的順序,同時保持字串的第一個和最後一個字元不變。

方法

解決此問題的策略很簡單:

  • 將輸入字串分割成單詞。

  • 交換第一個和最後一個單詞。

  • 反轉中間字元的順序,同時保持字串的第一個和最後一個字元在原始位置。

  • 將單詞重新連線成字串。

示例

下面是一個 Java 函式,實現了上述方法:

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 < words.length; i++) {
         if(words[i].length() > 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"));
   }
}

輸出

Jvaa wlrod tihs is Hlleo

解釋

讓我們用字串“Hello world this is Java”來測試我們的函式。

字串中的單詞是 ["Hello", "world", "this", "is", "Java"]。交換第一個和最後一個單詞後,我們得到 ["Java", "world", "this", "is", "Hello"]。

然後我們反轉每個單詞的中間字元,排除第一個和最後一個字元,得到 ["Jvaa", "wlrod", "tihs", "is", "Hlleo"]。

最後,我們將單詞重新連線成字串:“Jvaa wlrod tihs is Hlleo”。

因此,swapAndReverse("Hello world this is Java") 的輸出為 "Jvaa wlrod tihs is Hlleo"。

swapAndReverse 函式工作正常,並且很明顯它準確地交換了給定字串的首尾單詞並反轉了中間字元。我們希望此示例能夠闡明函式的操作。

結論

Java 提供了各種各樣的字串操作工具,使其非常適合解決諸如交換字串首尾單詞和反轉中間字元等問題。掌握這些技能將使你在編碼面試和日常程式設計任務中受益匪淺。

更新於: 2023年5月15日

302 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.