美文网首页Leetcode
Leetcode 557. Reverse Words in a

Leetcode 557. Reverse Words in a

作者: SnailTyan | 来源:发表于2018-10-26 19:36 被阅读1次

    文章作者:Tyan
    博客:noahsnail.com  |  CSDN  |  简书

    1. Description

    Reverse Words in a String III

    2. Solution

    class Solution {
    public:
        string reverseWords(string s) {
            int start = 0;
            for(int i = 0; i < s.length(); i++) {
                if(s[i] == ' ') {
                    reverse(s, start, i - 1);
                    start = i + 1;
                }
            }
            reverse(s, start, s.length() - 1);
            return s;
        }
        
    private:
        void reverse(string& s, int start, int end) {
            while(start < end) {
                swap(s[start++], s[end--]);
            }
        }
        
        void swap(char& a, char& b) {
            char temp = a;
            a = b;
            b = temp;
        }
    };
    

    Reference

    1. https://leetcode.com/problems/reverse-words-in-a-string-iii/description/

    相关文章

      网友评论

        本文标题:Leetcode 557. Reverse Words in a

        本文链接:https://www.haomeiwen.com/subject/ponzaftx.html