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.

Solution: Save the index of space

In this problem, we need to reserve the order of every words.

Note: We need to handle the last word, because there's might not be any empty space at the end.

string reverseWords(string s) {
    int index = -1;
    for (int i = 0; i < s.length(); i++) {
        if (s[i] == ' ' || i == s.length() - 1) {
            if (i == s.length() - 1) i++;

            int l = index + 1;
            int r = i - 1;
            while (l < r) swap(s[l++], s[r--]);
            index = i;
        }
    }
    return s;
}

results matching ""

    No results matching ""