1. 程式人生 > >LeetCode557 反轉字串中的單詞 III

LeetCode557 反轉字串中的單詞 III

給定一個字串,你需要反轉字串中每個單詞的字元順序,同時仍保留空格和單詞的初始順序。

示例 1:

輸入: "Let's take LeetCode contest"
輸出: "s'teL ekat edoCteeL tsetnoc" 

注意:在字串中,每個單詞由單個空格分隔,並且字串中不會有任何額外的空格。

 


 

 

//章節 - 陣列和字串    
//五、小結
//4.反轉字串中的單詞 III
/*
演算法思想:
    首先來看使用字元流處理類stringstream來做的方法,相當簡單,就是按順序讀入每個單詞進行翻轉即可。
*/ //演算法實現: class Solution { public: string reverseWords(string s) { string res = "", t = ""; istringstream is(s); while (is >> t) { reverse(t.begin(), t.end()); res += t + " "; } res.pop_back(); return res; } };
/* 演算法思想: 用兩個指標,分別指向每個單詞的開頭和結尾位置,確定了單詞的首尾位置後,再用兩個指標對單詞進行首尾交換即可,有點像驗證迴文字串的方法。 */ //演算法實現: /* class Solution { public: string reverseWords(string s) { int start = 0, end = 0, n = s.size(); while (start < n && end < n) { while (end < n && s[end] != ' ') ++end; for (int i = start, j = end - 1; i < j; ++i, --j) { swap(s[i], s[j]); } start = ++end; } return s; } };
*/