• LeetCode--Reverse Words in a String


    class Solution {
    public:
        void reverseWords(string &s) {
            int len = s.length();
            if(len == 0)
                return;
            vector<string> res;
            int i = 0;
            int j = len-1;
            //去掉收尾的空格
            while(i < len && s[i] == ' ')
                ++i;
            while(j >= 0 && s[j] == ' ')
                --j;
            int k = i;//寻找一个单词
            while(i <= j)
            {
                k = i;
                while(i<=j && s[i]!=' ')
                {
                    ++i;
                }
                res.push_back(s.substr(k,i-k));
                while(s[i]==' ' && i<=j)
                    ++i;
            }
            if(res.empty())
            {
                s = "";
                return;
            }
            reverse(res.begin(),res.end());
            string m = res[0];
            for(int i=1;i<res.size();i++){  
                m+=" ";  
                m+=res[i];  
            }  
            s=m; 
        }
    };

    先删除前后的空格,多个空格合并为一个空格输出。

  • 相关阅读:
    20201031
    20201028
    20201026
    20201027
    20201020
    ReentrantReadWriteLock原理分析
    java中Thread源码介绍
    CountDownLatch原理分析
    Semaphore原理分析
    AQS-共享模式分析
  • 原文地址:https://www.cnblogs.com/cane/p/3845016.html
Copyright © 2020-2023  润新知