zoukankan      html  css  js  c++  java
  • [LeetCode]题解(python):151-Reverse Words in a String

    题目来源:

      https://leetcode.com/problems/reverse-words-in-a-string/


    题意分析:

      给定一个字符串,里面包括多个单词,将这个字符串的单词翻转,例如"the sky is blue",得到"blue is sky the".


    题目思路:

      首先获取每个单词,将单词记录到一个数组里面,然后翻转过来就行了。要处理的是前面和后面有空格的情况。


    代码(python):

    class Solution(object):
        def reverseWords(self, s):
            """
            :type s: str
            :rtype: str
            """
            if len(s) == 0:
                return ""
            ans = []
            begin = i = 0
            mark = True
            while i < len(s):
                if s[i] != ' 'and mark:
                    begin = i
                    mark = False
                if s[i] == ' ' and i > 0 and s[i - 1] != ' ':
                    ans.append(s[begin:i])
                    while i < len(s) and s[i] == ' ':
                        i += 1
                    begin = i
                i += 1
            if s[-1] != ' ':
                ans.append(s[begin:len(s)])
            #print(ans)
            j = len(ans)
            if j == 0:
                return ""
            res = ans[j - 1]
            j -= 1
            while j > 0:
                res += ' ' + ans[j - 1]
                j -= 1
            return res
    View Code

      

  • 相关阅读:
    Linux上统计文件夹下文件个数
    linux----tail 过滤日志文件中的关键字
    Linux----Makefile
    Python--day 3
    Python--day 2
    Python--day 1
    Ubuntu14.04 64位网易云播放器
    qt 串口通信学习的目录
    qt layout 注意要点
    模拟电子第一章半导体
  • 原文地址:https://www.cnblogs.com/chruny/p/5478262.html
Copyright © 2011-2022 走看看