劍指 Offer 58 I 翻轉單詞順序

2021-10-12 18:21:06 字數 1178 閱讀 5692

1、題目描述

輸入乙個英文句子,翻轉句子中單詞的順序,但單詞內字元的順序不變。為簡單起見,標點符號和普通字母一樣處理。例如輸入字串"i am a student. 「,則輸出"student. a am i」。

示例 1:

輸入: 「the sky is blue」

輸出: 「blue is sky the」

示例 2:

輸入: " hello world! "

輸出: 「world! hello」

解釋: 輸入字串可以在前面或者後面包含多餘的空格,但是反轉後的字元不能包括。

示例 3:

輸入: 「a good example」

輸出: 「example good a」

解釋: 如果兩個單詞間有多餘的空格,將反轉後單詞間的空格減少到只含乙個。

2、方法

1)雙指標法倒序遍歷字串

(1)首先去掉字串的首尾空格:s = s.trim();

(2)用 left 和 right 分別標定單詞的左右邊界;

(3)不斷地左移 left,直到找到單詞前的第乙個空格或者左邊界越界;

(4)把字串的左邊界到右邊界的子串+「 」串接到stringbuilder中;

(5)不斷地左移 left,把該單詞前的所有空格都跳過去;

(6)把空格跳過去後,把單詞的右邊界 right 置為當前左邊界 right;

(7)執行第(3)-(6)步;

(8)把stringbuilder轉換為字串並去掉首尾空格:news = stringbuilder.tostring().trim();

public string reversewords

(string s)

stringbuilder.

(s.substring

(left +

1, right +1)

+" ");

while

(left >=

0&& s.

charat

(left)

==' '

) right = left;

} string news = stringbuilder.

tostring()

;return news.

trim()

;}

劍指 Offer 58 I 翻轉單詞順序

題目 leetcode上面這道題與書上有些許不同,leetcode還考慮句子首尾和末尾有空格的情況,以及單詞之間存在多個空格。思路1 class solution return res.tostring trim 思路2 先剔除字串首尾的空格,然後利用split 函式,根據空格劃分,返回乙個stri...

劍指 Offer 58 I 翻轉單詞順序

輸入乙個英文句子,翻轉句子中單詞的順序,但單詞內字元的順序不變。為簡單起見,標點符號和普通字母一樣處理。例如輸入字串 i am a student.則輸出 student.a am i 示例 1 輸入 the sky is blue 輸出 blue is sky the 示例 2 輸入 hello ...

劍指 Offer 58 I 翻轉單詞順序

輸入乙個英文句子,翻轉句子中單詞的順序,但單詞內字元的順序不變。為簡單起見,標點符號和普通字母一樣處理。例如輸入字串 i am a student.則輸出 student.a am i 示例 1 輸入 the sky is blue 輸出 blue is sky the 示例 2 輸入 hello ...