【LeetCode】151. Reverse Words in a String 解题报告(Python)

【LeetCode】151. Reverse Words in a String 解题报告(Python)

标签(空格分隔): LeetCode

作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.me/


题目地址:https://leetcode.com/problems/reverse-words-in-a-string/description/

题目描述:

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

Example:

Input: "the sky is blue",
Output: "blue is sky the".

Note:

  • A word is defined as a sequence of non-space characters.
  • Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.
  • You need to reduce multiple spaces between two words to a single space in the reversed string.

Follow up: For C programmers, try to solve it in-place in O(1) space.

题目大意

翻转字符串里面的单词。同时去掉多余的空格。

解题方法

首尾空格可以用strip()函数,重复空格使用正则表达式替换,最后split()再翻转即可。

class Solution(object):
    def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """
        s = s.strip()
        p = re.compile(r'\s{2,}')
        s = p.sub(" ", s)
        return " ".join(s.split()[::-1])

日期

2018 年 6 月 26 日 ———— 早睡早起

猜你喜欢

转载自blog.csdn.net/fuxuemingzhu/article/details/80810249