notes/OJ notes/pages/Leetcode Reverse-Words-In-a-String.md
2022-09-03 15:41:36 +08:00

1.5 KiB

Leetcode Reverse-Words-In-a-String

2022-07-12 09:10

Algorithms:

#algorithm #two_pointers

Data structures:

#DS #string

Difficulty:

#coding_problem #difficulty-easy

Additional tags:

#leetcode

Revisions:

N/A


Problem

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

Examples

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.

Thoughts

[!summary] This is a #two_pointers

very easy and intuitive.

Solution

class Solution {
  void reverse(string &s, int l, int r) {
    if (l >= r) {
      return;
    }
    swap(s[l++], s[r--]);
    reverse(s, l, r);
  }

public:
  string reverseWords(string s) {
    int slow = 0, fast;
    for (int i = 0; i < s.size(); i++) {
      if (s[i] == ' ') {
        fast = i - 1;
        reverse(s, slow, fast);
        slow = i + 1;
      }
    }
    reverse(s, slow, s.size() - 1);
    return s;
  }
};