1. 程式人生 > 其它 >翻轉字串裡的單詞

翻轉字串裡的單詞

此部落格連結:

翻轉字串裡的單詞

題目連結:https://leetcode-cn.com/leetbook/read/array-and-string/crmp5/

題目

給你一個字串 s ,逐個翻轉字串中的所有 單詞 。

單詞 是由非空格字元組成的字串。s 中使用至少一個空格將字串中的 單詞 分隔開。

請你返回一個翻轉 s 中單詞順序並用單個空格相連的字串。

說明:

輸入字串 s 可以在前面、後面或者單詞間包含多餘的空格。
翻轉後單詞間應當僅用一個空格分隔。
翻轉後的字串中不應包含額外的空格。

示例 1:

輸入:s = "the sky is blue"
輸出:"blue is sky the"
示例 2:

輸入:s = " hello world "
輸出:"world hello"
解釋:輸入字串可以在前面或者後面包含多餘的空格,但是翻轉後的字元不能包括。
示例 3:

輸入:s = "a good example"
輸出:"example good a"
解釋:如果兩個單詞間有多餘的空格,將翻轉後單詞間的空格減少到只含一個。
示例 4:

輸入:s = " Bob Loves Alice "
輸出:"Alice Loves Bob"
示例 5:

輸入:s = "Alice does not even like bob"
輸出:"bob like even not does Alice"

提示:

1 <= s.length <= 104
s 包含英文大小寫字母、數字和空格 ' '
s 中 至少存在一個 單詞

題解

使用空格,先把字串轉成字串陣列,對陣列進行翻轉,使用一個臨時變數,以字串陣列中間為軸,把字串陣列進行翻轉。

程式碼

class Solution {
    public String reverseWords(String s) {
        String t=s.trim();
    String str[]=t.split(" ");
    int len=str.length;
    //System.out.println(len);
    for(int i=0;i<len/2;i++){
        if(str[i]!=" "){
        String temp=str[i];
       str[i]= str[len-i-1];
       str[len
-i-1]=temp; } } String res=""; for(int i=0;i<len-1;i++){ res+=str[i]+" "; } res+=str[len-1]; return res; } }

結果

多空格沒有處理。