557. Reverse Words in a String III

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

Example 1:

Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"

Note: In the string, each word is separated by single space and there will not be any extra space in the string.

// stringstream
string reverseWords(string s) { // time: O(n); space: O(n)
    istringstream is(s);
    string buf, res;
    while (is >> buf) {
        reverse(buf.begin(), buf.end());
        res += buf + " ";
    }
    return res.substr(0, res.length() - 1);
}
string reverseWords(string s) { // time: O(n); space: O(n)
    int start = 0, end = 0, n = s.length();
    while (start < n && end < n) {
        while (end < n && s[end] != ' ') ++end;
        for (int i = start, j = end - 1; i < j; ++i, --j) {
            swap(s[i], s[j]);
        }
        start = ++end;
    }
    return s;
}
string reverseWords(string s) { // time: O(n); space: O(n)
    int n = s.length(), i = 0, j = 0;
    while (j < n) {
        while (j < n && s[j] != ' ') ++j;
        reverse(s.begin() + i, s.begin() + j);
        i = j + 1;
        j = i;
    }
    return s;
}

Last updated

Was this helpful?