zoukankan      html  css  js  c++  java
  • LeetCode:151_Reverse Words in a String | 字符串中单词的逆反 | Medium

    题目:Reverse Words in a String

    Given an input string, reverse the string word by word. 
    
    For example,
     Given s = "the sky is blue",
     return "blue is sky the". 

    比较基础的一个题,拿到这个题,我的第一想法是利用vector来存每一个子串,然后在输出,这是一个比较简单的思路,此外,还有第二个思路,就是对所有的字符反转,然后在针对每一个子串反转,但是这个时候要注意它的要求,保证每个子串中只有一个空格。我是按照第一种思路,代码如下:

     1 void reverseWords(string &s)
     2 {
     3     int i = 0, j = 0;
     4     string subStr;
     5     vector<string> vecStr;
     6     for (j = 0; j != s.length()+1; ++j) {
     7         if (s[j] == ' '||j == s.length()) { //Ensure that the final substr can be get
     8             subStr = s.substr(i, j - i);
     9             if (subStr != "")  //remove the "" from begin and end str
    10                 vecStr.push_back(subStr);
    11             i = j + 1;
    12         }
    13     }
    14     
    15     int vecLen = vecStr.size();
    16     if (vecLen > 0) {  // deal with the s = ""
    17         string strResult = "";
    18         for (i = vecLen - 1; i > 0; i --) {
    19             strResult += vecStr[i] + " ";
    20         }
    21         strResult += vecStr[i];
    22         s = strResult;
    23     }
    24     else
    25         s = "";
    26 }

    测试情况注意几种:首尾有" "的情况;有多个" "的情况;s = ""的情况;

    另外,看到有网友zhangyuehuan的专栏提供了一种更为简洁的思路:

    从字符串的最后一个字符遍历,遇到空格就保存子串,然后再对子串反转,和我上面的思路类似,只不过我的遍历方法是正向遍历的,但是其代码简洁,值得学习:

    void reverseWords(string & s)
    {
        string ss;
        int i = s.length()-1;
        while(i>=0)
        {
            while(i>=0&&s[i] == ' ') //处理多个空格的情况
            {
                i --;
            }
            if(i<0) break;
            if(ss.length()!=0)
                ss.push_back(' ');
            string temp ;
            for(;i>=0&&s[i]!=' ';i--)
                temp.push_back(s[i]);
            reverse(temp.begin(),temp.end());
            ss.append(temp);
        }
        s=ss;
    }
  • 相关阅读:
    AsyncHttpClient使用
    索引
    jdbc--取大量数据
    oracle--with as
    spring--mybatis事务总结
    Elasticsearch环境搭建
    使用idea远程调试
    redis分布式锁的实现
    知识梳理
    Zookeeper
  • 原文地址:https://www.cnblogs.com/bakari/p/3993427.html
Copyright © 2011-2022 走看看