題目:
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
click to show clarification.
Clarification:思路:
這題的思路不用多說,完全是爛大街的題,不就是先以每個單詞為單位,進行翻轉,再以整句話為單位進行翻轉嗎?呵呵,太簡單了,以為簡單你就能做對那可就大錯特錯了,題干裡的的說明還要求去除首尾空格,並壓縮多個空格為一個空格,所以會有N多邊界條件要考慮,我竟然編譯了N次才通過leetcode OJ,作為一個正式工作一年多的程序員,實在是對不起國家,邊界條件的確是考察一個人思維嚴謹性甚至記憶力的試金石!
代碼:
class Solution {
public:
Solution(){}
void reverse(std::string &s, int f, int e)
{
while (e>f)
{
char tmp = s.at(f);
s.at(f) = s.at(e);
s.at(e) = tmp;
f++;
e--;
}
}
void squeeze(std::string &s)
{
int i = 0;
std::string re = "";
char prev = NULL;
bool flag = false;
while (i < s.size())
{
if (s.at(i)!=' ')
{
if (flag&&prev == ' ')
{
re.push_back(' ');
}
re.push_back(s.at(i));
}
if (s.at(i) == ' '&&prev !=NULL &&prev!= ' ')
{
flag = true;
}
prev = s.at(i);
i++;
}
s = re;
}
void reverseWords(std::string &s) {
int i = 0;
int f=0, e=0;
char prev = ' ';
while (i