返回介绍

solution / 0100-0199 / 0186.Reverse Words in a String II / README_EN

发布于 2024-06-17 01:04:03 字数 3563 浏览 0 评论 0 收藏 0

186. Reverse Words in a String II

中文文档

Description

Given a character array s, reverse the order of the words.

A word is defined as a sequence of non-space characters. The words in s will be separated by a single space.

Your code must solve the problem in-place, i.e. without allocating extra space.

 

Example 1:

Input: s = ["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"]

Example 2:

Input: s = ["a"]
Output: ["a"]

 

Constraints:

  • 1 <= s.length <= 105
  • s[i] is an English letter (uppercase or lowercase), digit, or space ' '.
  • There is at least one word in s.
  • s does not contain leading or trailing spaces.
  • All the words in s are guaranteed to be separated by a single space.

Solutions

Solution 1

class Solution:
  def reverseWords(self, s: List[str]) -> None:
    """
    Do not return anything, modify s in-place instead.
    """

    def reverse(s, i, j):
      while i < j:
        s[i], s[j] = s[j], s[i]
        i += 1
        j -= 1

    i, j, n = 0, 0, len(s)
    while j < n:
      if s[j] == ' ':
        reverse(s, i, j - 1)
        i = j + 1
      elif j == n - 1:
        reverse(s, i, j)
      j += 1
    reverse(s, 0, n - 1)
class Solution {
  public void reverseWords(char[] s) {
    int n = s.length;
    for (int i = 0, j = 0; j < n; ++j) {
      if (s[j] == ' ') {
        reverse(s, i, j - 1);
        i = j + 1;
      } else if (j == n - 1) {
        reverse(s, i, j);
      }
    }
    reverse(s, 0, n - 1);
  }

  private void reverse(char[] s, int i, int j) {
    for (; i < j; ++i, --j) {
      char t = s[i];
      s[i] = s[j];
      s[j] = t;
    }
  }
}
class Solution {
public:
  void reverseWords(vector<char>& s) {
    int n = s.size();
    for (int i = 0, j = 0; j < n; ++j) {
      if (s[j] == ' ') {
        reverse(s, i, j - 1);
        i = j + 1;
      } else if (j == n - 1) {
        reverse(s, i, j);
      }
    }
    reverse(s, 0, n - 1);
  }

  void reverse(vector<char>& s, int i, int j) {
    for (; i < j; ++i, --j) {
      swap(s[i], s[j]);
    }
  }
};
func reverseWords(s []byte) {
  n := len(s)
  for i, j := 0, 0; j < n; j++ {
    if s[j] == ' ' {
      reverse(s, i, j-1)
      i = j + 1
    } else if j == n-1 {
      reverse(s, i, j)
    }
  }
  reverse(s, 0, n-1)
}

func reverse(s []byte, i, j int) {
  for i < j {
    s[i], s[j] = s[j], s[i]
    i++
    j--
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文