題目來源:
題目描述:
Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: "Let's take LeetCode contest" Output: "s'teL ekat edoCteeL tsetnoc"
Note: In the string, each word is separated by single space and there will not be any extra space in the string.
我的解決方案:
class Solution {
public:
string reverseWords(string s) {
string ret,tmp;
for(int i=0;i<s.size();++i)
{
if(s[i]!=' ')
tmp.insert(0,1,s[i]);
else
{
ret.append(tmp);
if(i!=s.size()-1)
{
ret.insert(ret.size(),1,' ');
tmp.clear();
}
}
}
ret.append(tmp);
return ret;
}
};
第一遍的錯誤解法:
class Solution {
public:
string reverseWords(string s) {
string ret,tmp;
for(int i=0;i<s.size();++i)
{
if(s[i]!=' ')
tmp.insert(0,1,s[i]);
else
{
ret.append(tmp);
ret.insert(ret.size(),1,' ');
tmp.clear();
}
}
return ret;
}
};
思考:
閱讀題目描述,第一反應是分塊反轉每個單詞,遇到空格停止,用一個臨時變量來存儲和反轉每個單詞,完成一個單詞的反轉之後,插入一個空格,追加到結果中,遍歷完成來源string之後就完成了.題目不難,如果對對C++的string類的操作比較熟悉,就可以節省很多力氣.第一遍寫出來的代碼結果有點問題,原因是因爲來源string的末尾並沒有空格,導致最後一次循環的時候else沒有按照預想的執行,保存了反轉後字符的tmp沒有被追加到ret之後,所以輸出少了一個單詞.所以對最後一次進行了特殊處理,然後ac了
後來看別人的代碼,發現還有更簡單的方法,這裏做一個引用(引用自Sublele,侵刪)
class Solution {
public:
string reverseWords(string s) {
size_t front = 0;
for(int i = 0; i <= s.length(); ++i){
if(i == s.length() || s[i] == ' '){
reverse(&s[front], &s[i]);
front = i + 1;
}
}
return s;
}
};
其中,reverse(front,end)函數的作用是反轉一個容器內從front到end的所有內容