您的位置:首页 > 编程语言 > Python开发

【LeetCode with Python】 Reverse Words in a String

2008-12-07 13:04 756 查看
博客域名:http://www.xnerv.wang

原题页面:https://oj.leetcode.com/problems/reverse-words-in-a-string/

题目类型:字符串,两指针问题

难度评价:★

本文地址:/article/1377552.html

Given an input string, reverse the string word by word.

For example,

Given s = "
the sky is blue
",

return "
blue is sky the
".

click to show clarification.
Clarification:

What constitutes a word?

A sequence of non-space characters constitutes a word.
Could the input string contain leading or trailing spaces?

Yes. However, your reversed string should not contain leading or trailing spaces.
How about multiple spaces between two words?

Reduce them to a single space in the reversed string.

反转一句话中的单词。注意题中还要求去除首尾可能存在的空白字符,词与词之间也要去除多余空白字符,而只留一个空白。

class Solution:

    # @param s, a string
    # @return a string
    def reverseWords(self, s):

        len_s = len(s)
        if len_s < 1:
            return s

        index_right = len_s - 1
        new_s = ""

        while index_right >= 0:
            while index_right >= 0 and ' ' == s[index_right]:
                index_right -= 1
            end_index = index_right
            while index_right >= 0 and ' ' != s[index_right]:
                index_right -= 1
            start_index = index_right + 1
            word = s[start_index : end_index + 1] if end_index >= 0 else ""
            new_s += (word + " ")

        return new_s.rstrip()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: