Leetcode 151. Reverse Words in a String

Posted mfcheer

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 151. Reverse Words in a String相关的知识,希望对你有一定的参考价值。

题目:https://leetcode.com/problems/reverse-words-in-a-string/

代码:

class Solution 

public:
    void reverseWords(string &s)
    
        string ans;
        ans.clear();
        for (int i = 0;i != s.size() / 2;i++)
            swap(s[i], s[s.size() - i - 1]);
        string tmp;

        for (int i = 0;i < s.size();i++)
        
            if (s[i] != ' ')
                tmp.push_back(s[i]);

            else if (tmp.size() != 0)
            
                for (int j = 0;j != tmp.size() / 2;j++)
                    swap(tmp[j], tmp[tmp.size() - j - 1]);
                if (ans.size() != 0)
                    ans.append(" ");
                ans += tmp;
                tmp.clear();
            
        

        if (tmp.size() != 0)
        
            if (ans.size() != 0)
                ans.append(" ");
            for (int j = 0;j != tmp.size() / 2;j++)
                swap(tmp[j], tmp[tmp.size() - j - 1]);
            ans += tmp;
        
        s.clear();
        s = ans;
    
;

以上是关于Leetcode 151. Reverse Words in a String的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode151. Reverse Words in a String

刷题-LeetCode151 Reverse Words in a String

Leetcode 151. Reverse Words in a String 解题报告

leetcode 151. Reverse Words in a String --------- java

leetcode-151-reverse word in a string

leetcode-Reverse Words in a String-151