Reverse Words in a String
Problem:
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
這個題目敘述的不夠精確,有些邊界的情況需要考慮。題目的下方給出了Clarification澄清了幾個問題,也是面試的時候需要確認的。
第一個問題是什么構成了一個詞(word),回答是一串不包含空格(non-space)的字符。這里需要理解non-space,應該要包含' ', '\t', '\n'等字符,C語言中可以通過宏定義isspace來判斷。
第二個問題是詞的開頭與結尾能有空格嗎,回答是有的,但返回的結果中應該去掉。
第三個問題是分隔每兩個詞之間的空格能有多個嗎,回答是能,但返回結果中應該只留下一個空格就好。
通過詢問這三個問題,題目也就清楚多了,這個題目的解決思路并不困難,就是先翻轉每個單詞,再對整個字符串翻轉就能做到翻轉每個單詞的目的,但是同時要想將單詞間的空格變為一個,頭尾都要去掉就要費一番功夫。
我的解法是直接在原始的字符串上一遍掃描,從后向前翻轉單詞,同時將單詞移位到正確的位置,即每兩個單詞之間保證只有一個空格。然后整體再翻轉一次,只有結尾處還可能有些空格,再單獨處理。代碼中使用了algorithm中的reverse來翻轉字符串,效率可能會稍差,可以自己直接用下標操作,寫個翻轉函數。
1 void reverseWords(string &s) { 2 int len = s.length(); 3 4 // find each word iteratively and then reserve it 5 int align = len-1; 6 int start_pos, end_pos; 7 for(int i = len-1; i >= 0; --i) { 8 if(!isspace(s[i])) { 9 end_pos = i; 10 11 while(i >= 0 && !isspace(s[i])) { 12 --i; 13 } 14 start_pos = i+1; 15 16 reverse(s.begin()+start_pos, s.begin()+end_pos+1); 17 18 if(end_pos != align) { 19 for(int j = 0; j <= end_pos-start_pos; ++j) { 20 s[align-j] = s[end_pos-j]; 21 } 22 } 23 align -= (end_pos-start_pos+1); 24 if(align >= 0) { 25 s[align--]= ' '; 26 } 27 } 28 } 29 30 if(align >= 0) { 31 fill(s.begin(), s.begin()+align+1, ' '); 32 } 33 34 // reverse the whole string and trim the leading and trailing spaces 35 reverse(s.begin(), s.end()); 36 37 int i = len-1; 38 while(i >= 0 && isspace(s[i])) 39 --i; 40 s = s.substr(0, i+1); 41 }?
轉載于:https://www.cnblogs.com/foreverinside/p/3694630.html
總結
以上是生活随笔為你收集整理的Reverse Words in a String的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【原】移动web动画设计的一点心得——c
- 下一篇: PhpMyAdmin导入数据库大小限制?