Skip to content

Latest commit

 

History

History
76 lines (65 loc) · 2.62 KB

README.md

File metadata and controls

76 lines (65 loc) · 2.62 KB

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

 

Example 1:

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

Example 2:

Input: s = "God Ding"
Output: "doG gniD"

 

Constraints:

  • 1 <= s.length <= 5 * 104
  • s contains printable ASCII characters.
  • s does not contain any leading or trailing spaces.
  • There is at least one word in s.
  • All the words in s are separated by a single space.

Companies: Yandex, Microsoft, Apple, Facebook, Amazon, Google, Bolt, Bloomberg, Paytm, Zappos

Related Topics:
Two Pointers, String

Similar Questions:

Solution 1.

// OJ: https://leetcode.com/problems/reverse-words-in-a-string-iii
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
    string reverseWords(string s) {
        int N = s.size();
        for (int i = 0; i < N; ++i) {
            int j = i;
            while (j < N && s[j] != ' ') ++j;
            int next = j;
            for (--j; i < j;) swap(s[i++], s[j--]);
            i = next;
        }
        return s;
    }
};

Or

// OJ: https://leetcode.com/problems/reverse-words-in-a-string-iii
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
    string reverseWords(string s) {
        for (int i = 0, begin = 0, N = s.size(); i <= N; ++i) {
            if (i == N || s[i] == ' ') {
                reverse(s.begin() + begin, s.begin() + i);
                begin = i + 1;
            }
        }
        return s;
    }
};