1. 程式人生 > >LeetCode OJ :Reverse Words in a String

LeetCode OJ :Reverse Words in a String

LeetCode OJ上的一道題,題目要求如下:

Given an input string, reverse the string word by word.

For example,
Given s = "the sky is blue",
return "blue is sky the"

第一次提交了才發現自己考慮的還不夠全面,下面再舉幾個例子:

Given s="   " return ""

Given s="  a   b    " return "a b"

接下來給出我最後提交的版本,個人體會,這道題主要還是側重於考慮問題的完整性上:

class Solution {
public:
    void reverseWords(string &s) {
        int i=0,num=0;//num用來記錄字串中單詞的長度
        string temp;
        while(s[0]==' ') s=s.substr(1,s.size()-1);//用來消去字串前面的空格
        int last=s.size()-1;
        while(s[last]==' ') {//用來消去字串後面的空格
            last--;
            s=s.substr(0,s.size()-1);
        }
        for(i=s.size();i>=0;i--){//定位每個單詞的範圍
            if(s[i]==' '){
                temp=temp+s.substr(i+1,num)+" ";//複製單詞到temp中
                num=0;
                last=i-1;
                while(s[i-1]==' '){
                    i--;
                    last=i-1;
                }
            }		
            else
                num++;
        }
        s=temp+s.substr(0,last+1);//執行退出for迴圈之後的最後一個單詞的操作
    }
};