鱼C论坛

 找回密码
 立即注册
查看: 1056|回复: 0

[技术交流] 【朱迪的LeetCode刷题笔记】151. Reverse Words in a String #Medium #Python #C++

[复制链接]
发表于 2023-6-3 12:04:27 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 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[i] != "":
                rlst.append(lst[i])
        return " ".join(rlst)

Sol1
Python
https://leetcode.com/problems/re ... 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/re ... /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[i] != ' ') {
                word = s[i] + word;
            } else {
                if (word.size() > 0) {
                    reverse += word + " ";
                    word = "";
                }
            }
        }
        if (word.size() > 0) {
            reverse += word;
        }
        if (reverse[reverse.size() - 1] == ' ') {
            reverse.pop_back();
        }
        return reverse;
    }

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-11-22 08:59

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表