首页 > 试题广场 >

翻转单词序列

[编程题]翻转单词序列
  • 热度指数:683507 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 64M,其他语言128M
  • 算法知识视频讲解
牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“nowcoder. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a nowcoder.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?

数据范围:
进阶:空间复杂度 ,时间复杂度 ,保证没有只包含空格的字符串
示例1

输入

"nowcoder. a am I"

输出

"I am a nowcoder."
示例2

输入

""

输出

""
推荐
public class Solution {
    public String ReverseSentence(String str) {
        if(str.trim().equals("")){
            return str;
        }
        String[] a = str.split(" ");
        StringBuffer o = new StringBuffer();
        int i;
        for (i = a.length; i >0;i--){
            o.append(a[i-1]);
            if(i > 1){
                o.append(" ");
            }
        }
        return o.toString();
    }
}

编辑于 2015-06-19 17:23:02 回复(45)
class Solution:
    def ReverseSentence(self, s):
        # write code here
        li = s.split(' ')
        st = ''
        while li:
            st = st + li.pop(-1)+ ' '
#         return st.strip(' ')
        return st[:-1]
发表于 2021-05-05 14:11:45 回复(0)
# -*- coding:utf-8 -*-
class Solution:
    def ReverseSentence(self, s):
        # write code here
        array=s.split(' ')
        array=array[::-1]
        return ' '.join(array)

发表于 2021-05-03 15:58:35 回复(0)
Python字符串操作,s.isspace()是否是空格(s.isdigit(), s.isalpha(), ...),然后用空格分隔,反序。
# -*- coding:utf-8 -*-
class Solution:
    def ReverseSentence(self, s):
        # write code here
        if s.isspace():
            return s
        rwords=list(s.split())
        output=''
        for x in range(len(rwords)-1,-1,-1):
            output+=rwords[x]
            if x>0:
                output+=' '
        return output

发表于 2021-04-17 20:55:13 回复(0)

python解法:

# -*- coding:utf-8 -*-
'''
解法1:创建一个数组,存储单词,之后再反转,不能直接反转s,因为s里面存储的是字符;
'''
class Solution:
    def ReverseSentence(self, s):
        res = []
        st = ''
        for i in s:
            if i != ' ':
                st += i
            else:
                res.append(st)
                res.append(' ')
                st = ''
        res.append(st)
        res.reverse()
        return ''.join(res)
发表于 2021-02-19 18:00:44 回复(0)
python 一行解法

class Solution:
    def ReverseSentence(self, s):
        # write code here
        return " ".join(s.split(" ")[::-1])


发表于 2021-01-22 05:09:16 回复(0)
# -*- coding:utf-8 -*-
class Solution:
    def ReverseSentence(self, s):
        # write code here
        s=s.split(' ')[::-1]
        return ' '.join(s)

发表于 2020-11-29 15:08:48 回复(0)
# -*- coding:utf-8 -*-
class Solution:
    def ReverseSentence(self, s):
        # write code here
        words = s.split(' ')
        res = []
        while words:
            res.append(words.pop())
        return " ".join(res)

发表于 2020-10-16 15:33:40 回复(0)
# -*- coding:utf-8 -*-
class Solution:
    def ReverseSentence(self, s):
        # write code here
        l = s.split(" ")
        return " ".join(l[::-1])

发表于 2020-07-30 09:47:51 回复(0)
class Solution:
    def ReverseSentence(self, s):
        a = s.split(' ')
        sentence=''
        for i in range(len(a)):
            sentence += a[len(a)-1-i] +' '
        return sentence[0:-1]

发表于 2020-07-09 20:53:48 回复(0)
# -*- coding:utf-8 -*-
class Solution:
    def ReverseSentence(self, s):
        # write code here
        s1 = s.split(' ')  # 将句子以空格分隔为一个数组
        s2 = list(reversed(s1))    # 将数组逆序显示
        s3 = ' '.join(s2)    # 重新由数组变为字符串
        return s3

发表于 2020-05-28 14:28:52 回复(0)
        l1=s.split(" ")
        l2=[]
        n=len(l1)-1
        while n>=0:
            l2.append(l1[n])
            n=n-1
        return(' '.join(l2))

发表于 2020-05-22 15:10:50 回复(0)
class Solution:
    def ReverseSentence(self, s):
        # write code here
        s = s.split(" ")[::-1]
        res = ""
        for i in range(len(s)-1):
            res += s[i]+" "
        return res+s[-1]
发表于 2020-03-21 16:18:10 回复(0)

可以处理两头有空格以及有多个空格的情况

# -*- coding:utf-8 -*-
class Solution:
    def ReverseSentence(self, s):
        # write code here
        def Reverse(l, p1, p2):
            while p1 < p2:
                l[p1], l[p2] = l[p2], l[p1]
                p1 += 1
                p2 -= 1

        if not s:
            return s
        l = []
        for each in s:
            l.append(each)
        Reverse(l, 0, len(l) - 1)

        head = 0
        tail = 0
        while head < len(l):
            if l[head] == ' ':
                head += 1
            else:
                tail = head + 1
                while tail < len(l):
                    if l[tail] != ' ':
                        tail += 1
                    else:
                        break
                Reverse(l, head, tail - 1)
                head = tail
        return ''.join(l)
编辑于 2020-03-12 23:29:04 回复(0)
# -*- coding:utf-8 -*-
class Solution:
    def ReverseSentence(self, s):
        return " ".join(s.split(" ")[::-1])


s = Solution()
ans = s.ReverseSentence("I am a student.")
print(ans)

发表于 2020-03-03 15:28:04 回复(0)
class Solution:
    def ReverseSentence(self, s):
        # write code here
        list1=s.split(' ')
        #将字符串以空格为间隔划分列表
        if len(list1)<=1:
            #不管是对于空字符串还是单个字符串,返回该字符串就行了
            return s
        return ' '.join(list1[::-1])
以空格为间隔将字符串划分成列表,如果列表长度小于等于1,则直接返回s就行了。其中s可以是“”或者“ ”等等,我们不用考虑。最后使用‘ ’.join(列表)的方法,将列表元素以空格形式,拼成一个字符串
发表于 2020-01-07 11:57:55 回复(0)
# -*- coding:utf-8 -*-
class Solution:
    def ReverseSentence(self, s):
        # write code here
        temp_string = s.split(" ")
        ans = ''
        for i in range(len(temp_string) - 1, -1, -1):
            if i != 0:
                ans += temp_string[i] + ' '
            else:
                # 最后一个特判
                ans += temp_string[i]
        return ans

发表于 2019-12-09 22:23:54 回复(0)
用Python中常用的join和split方法
# -*- coding:utf-8 -*-
class Solution:
    def ReverseSentence(self, s):
        t_list=s.split(' ')
        return ' '.join(t_list[::-1])


发表于 2019-11-11 13:01:01 回复(0)
思路是评论区大佬们给哒!想让大家给我提提意见呀~~
首先是先反转句子,再反转单词:
# -*- coding:utf-8 -*-
class Solution:
    def ReverseSentence(self, s):
        # write code here
        # 1. 先反转句子再反转单词  I ma a .tneduts
        if len(s)<1:
             return s
        s = list(s)
        s.reverse()       # 先反转句子
        lenList = len(s)
        i = 0
        ans = []
        
        def reverseWord(word):  #list输入,反转单词
            lenWord = len(word) 
            if lenWord == 0:
                return word
            i, j = 0, lenWord-1
            while i<j:
                word[i], word[j] = word[j], word[i]
                i += 1
                j -= 1  
            return word    # list输出
        
        while i < lenList:   
            if s[i]==" ":          # 如果有多个空格也可以加·
                ans.append(s[i])
                i += 1
                continue
            word = []
            while i<lenList and s[i] !=' ':
                word.append(s[i])
                i += 1
            word = reverseWord(word)
            for let in word:
                ans.append(let) 
                
        return "".join(ans)
接下来是先反转单词再反转句子。。基本换一下顺序就好了
# -*- coding:utf-8 -*-
class Solution:
    def ReverseSentence(self, s):
        # 先反转单词再反转句子
        if len(s)<1:
            return s
        s = list(s)
        lenList = len(s)
        i = 0
        ans = []
        sth = []
        
        def reversesth(sth):
            if len(sth)<=1:
                return sth
            i, j = 0, len(sth)-1
            while i<j:
                sth[i], sth[j] = sth[j], sth[i]
                i += 1
                j -= 1
            return sth
        
        while i<lenList:
            if s[i]==' ':
                ans.append(s[i])
                i += 1
                continue
            sth = []
            while i<lenList and s[i]!=' ':
                sth.append(s[i])
                i += 1
            sth = reversesth(sth)
            for item in sth:
                ans.append(item)
        ans = reversesth(ans)
        return "".join(ans)
        


发表于 2019-10-17 00:50:48 回复(0)
# -*- coding:utf-8 -*-
class Solution:
    def ReverseSentence(self, s):
        # write code here
        l = s.split(' ')
        return ' '.join(l[::-1])
发表于 2019-10-11 18:31:45 回复(0)
class Solution:
    def ReverseSentence(self, s):
        # write code here
        if not s:
            return ""
        split_words = s.split(" ")
        return " ".join(split_words[::-1])

人生苦短,我用 Python
发表于 2019-08-27 20:38:05 回复(0)

问题信息

难度:
58条回答 126754浏览

热门推荐

通过挑战的用户

查看代码