zoukankan      html  css  js  c++  java
  • 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及核心的数据结构,数据排序,查找算法。

  • 相关阅读:
    css hack
    纯DIV+CSS制作的三级鼠标经过弹出下拉导航菜单源码
    题解 Luogu P3863 序列
    破解SA的密码的方法
    转 三种方法实现实时切换CSS样式
    SQL Server 性能优化工具(1)
    Sql server中时间查询的一个比较快的语句
    转 CodeForFun编写自动登录Email的程序
    ISAPI_rewrite中文手册
    ASP.NET中实现二级或多级域名(修改UrlRewrite)
  • 原文地址:https://www.cnblogs.com/bestwangjie/p/4181063.html
Copyright © 2011-2022 走看看