LeetCode 5:Given an input string, reverse the string word by word.

problem:

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

For example:

Given s = "the sky is blue",

return "blue is sky the".

问题分析:如何准确的找到每一个需要清除的空格的位置pos,以及每个word对应的pos范围?

解决方法:需要反转一个字符串,使用int string.find_last_not_of(char c, int pos=npos);该函数是从字符串最后往前搜索最后一个不是字符c的位置.

在使用int string.find_first_of(char c, int pos=npos);该函数是从pos从后往前搜索第一个c出现的位置,并且返回。

还有要说明的是string& string.assign(const string &s, int start, int n);该函数是将s中从start出开始的n个字符赋给当前字符串。

基于上面的说明代码如下:

class Solution
{
    public:    
    void reverseWords(string &s)
{
    string strTmp;
    string Dst;

    size_t nLastWord  = s.find_last_not_of(" ");
    size_t nLastSpace = string::npos;

    while( nLastWord != string::npos )
    {
        nLastSpace = s.find_last_of(" ", nLastWord);
        if (nLastSpace == string::npos)
        {
            strTmp.assign(s, 0, nLastWord + 1);
            Dst += strTmp;

            break;
        } 
        else
        {
            strTmp.assign(s, nLastSpace + 1, nLastWord - nLastSpace);
            Dst += strTmp;
        }

        nLastWord = s.find_last_not_of(" ", nLastSpace);
        if (nLastWord == string::npos)
        {
            continue;
        }

        Dst += " ";
    }

    s = Dst;
}
};

感谢那些无偿贴出自己程序的供我学习的大神。
总结:基础知识很不扎实,还需要深入学习掌握STL及核心的数据结构,数据排序,查找算法。

原文地址:https://www.cnblogs.com/bestwangjie/p/4181063.html