马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
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
Pythonclass 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;
}
|