【LeetCode with Python】 Reverse Words in a String

来源:互联网 发布:阿里云 code 代码托管 编辑:程序博客网 时间:2024/06/05 13:09
博客域名:http://www.xnerv.wang
原题页面:https://oj.leetcode.com/problems/reverse-words-in-a-string/
题目类型:字符串,两指针问题
难度评价:★
本文地址:http://blog.csdn.net/nerv3x3/article/details/3465547

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()