Solved
Given an input string s
, reverse the order of the words.
A word is defined as a sequence of non-space characters. The words in s
will be separated by at least one space.
Return a string of the words in reverse order concatenated by a single space.
Note that s
may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.
Example 1:
Input: s = "the sky is blue" Output: "blue is sky the"
Example 2:
Input: s = " hello world " Output: "world hello" Explanation: Your reversed string should not contain leading or trailing spaces.
Example 3:
Input: s = "a good example" Output: "example good a" Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.
Constraints:
1 <= s.length <= 104
s
contains English letters (upper-case and lower-case), digits, and spaces' '
.- There is at least one word in
s
.
Follow-up: If the string data type is mutable in your language, can you solve it in-place with
O(1)
extra space? google 翻譯:
給定一個輸入字串 s,反轉單字的順序。
單字被定義為非空格字元的序列。 s 中的單字將至少由一個空格分隔。
傳回由單一空格以相反順序連接的單字字串。
請注意,s 可能在兩個單字之間包含前導或尾隨空格或多個空格。 傳回的字串應該只有一個空格來分隔單字。
請勿包含任何額外空格。
想法一:
從字串尾開始,用 while 往前找到空格,就把目前的字串,
一個字元一個字元的往後依序給要回傳的buf。
給完再繼續往前找,找到字串沒有為止。
寫法一:
char* reverseWords(char* s) {
char *str = malloc(strlen(s)+1);
char *p1 = s + strlen(s) - 1; // 字串尾
char *p2; // 找到的單字開頭
char *p_str = str; // 要回傳的字串
// 用 while 從字串尾開始往前找
while(p1 >= s) {
// 找到空格或已經開頭為止(意思是找到這個單字結束)
while(p1 > s && *p1 && *p1 != ' ')
p1--;
// 單字開頭
p2 = (*p1 != ' ') ? p1 : p1+1;
// 回傳的字串是否加空格
if(*p2 && *p2 != ' ' && p_str != str)
*p_str++ = ' ';
// 把找到的單字指定到回傳的字串裡
while(*p2 && *p2 != ' ')
*p_str++ = *p2++;
p1--; // 往前
}
*p_str = '\0'; // 字串結束
return str;
}
結果一:
結果尚可接受,但參考大神的寫法後,好像沒有想改的部份... 就這樣吧...
沒有留言:
張貼留言