Judie 发表于 2023-6-3 12:04:27

【朱迪的LeetCode刷题笔记】151. Reverse Words in a String #Medium #Python #C++

本帖最后由 Judie 于 2023-6-2 23:07 编辑

Given an input string 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 at least one space.

Return a string of the words in reverse order concatenated by a single space.

Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.

Example 1:
Input: s = "the sky is blue"
Output: "blue is sky the"

Example 2:
Input: s = "hello world"
Output: "world hello"
Explanation: Your reversed string should not contain leading or trailing spaces.

Example 3:
Input: s = "a good   example"
Output: "example good a"
Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.

Constraints:
1 <= s.length <= 104
s contains English letters (upper-case and lower-case), digits, and spaces ' '.
There is at least one word in s.

Follow-up:
If the string data type is mutable in your language, can you solve it in-place with O(1) extra space?

Judy
Python
class Solution(object):
    def reverseWords(self, s):
      """
      :type s: str
      :rtype: str
      """
      lst = s.split(" ")
      rlst = []
      l = len(lst)
      for i in range(l-1,-1,-1):
            if lst != "":
                rlst.append(lst)
      return " ".join(rlst)

Sol1
Python
https://leetcode.com/problems/reverse-words-in-a-string/solutions/2809269/python-3-line-code-easy-solution/
class Solution(object):
    def reverseWords(self, s):
      lst = s.split()
      lst = lst[::-1]
      return ' '.join(lst)

Sol2
Python
https://leetcode.com/problems/reverse-words-in-a-string/solutions/2810978/one-liner/
class Solution:
    def reverseWords(self, s: str) -> str:
      return ' '.join(reversed(s.split()))

Mike
C++
tring reverseWords(string s) {
      string reverse = "";
      string word = "";
      for (int i = s.size() - 1; i >= 0; i--) {
            if (s != ' ') {
                word = s + word;
            } else {
                if (word.size() > 0) {
                  reverse += word + " ";
                  word = "";
                }
            }
      }
      if (word.size() > 0) {
            reverse += word;
      }
      if (reverse == ' ') {
            reverse.pop_back();
      }
      return reverse;
    }

页: [1]
查看完整版本: 【朱迪的LeetCode刷题笔记】151. Reverse Words in a String #Medium #Python #C++