[LeetCode] Reverse Words in a String III

557. Reverse Words in a String III

Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

class Solution {
    void reverse(string& s, int l, int r) {
        while(l < r) {
            swap(s[l],s[r]);
            l++; r--;
        }
    }
public:
    string reverseWords(string s) {
        int l = s[0] == ' ' ? 1 : 0, r = s[0] == ' ' ? 1 : 0;
        while(l < s.length()) {
            while(r < s.length() and s[r] != ' ') r++;
            r--;
            reverse(s, l, r);
            l = r = r+=2;
        }
        return s;
    }
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/12/PS/LeetCode/reverse-words-in-a-string-iii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.