186. Reverse Words in a String II

Given an input string , reverse the string word by word.

Example:

Input:  ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"]
Output: ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"]

Note:

  • A word is defined as a sequence of non-space characters.

  • The input string does not contain leading or trailing spaces.

  • The words are always separated by a single space.

Follow up: Could you do it in-place without allocating extra space?

void reverseWords(vector<char>& str) { // time: O(n); space: O(1)
    reverse(str.begin(), str.end());
    int i = 0, n = str.size();
    for (int j = 0; j <= n; ++j) {
        if (j == n || str[j] == ' ') {
            reverse(str.begin() + i, str.begin() + j);
            i = j + 1;
        }
    }
}
void reverseWords(vector<char>& str) { // time: O(n); space: O(1)
    reverse(str.begin(), str.end());
    for (int i = 0, j = 0; i < str.size(); i = j + 1) {
        for (j = i; j < str.size(); ++j) {
            if (str[j] == ' ') break;
        }
        reverse(str.begin() + i, str.begin() + j);
    }
}
151. Reverse Words in a String

Last updated

Was this helpful?