LintCode翻转字符串问题 - python实现

题目描述:试实现一个函数reverseWords,该函数传入参数是一个字符串,返回值是单词间做逆序调整后的字符串(只做单词顺序的调整即可)。

例如:传入参数为"the sky is blue   ",调整后的字符串为“blue is sky the”。

解题思路:先将字符串转换成字符数组的形式,然后对"the sky is blue   "整体做逆序调整,得到['e', 'u', 'l', 'b', ' ', 's', 'i', ' ', 'y', 'k', 's', ' ', 'e', 'h', 't'];然后再寻找每个单词边界,对每个单词做逆序的调整,最终连接成字符串即可。

def reverseWords(s):
    """单词间逆序
    """
    s = s.strip(' ') # 去除首位空格
    if s == None or len(s) == 0:
        return None

    s = list(s)[::-1]

    # 寻找单词边界并作单词的逆序调整
    start = -1
    end = -1
    for i in range(len(s)):
        if s[i] != ' ':
            start = i if (i==0 or s[i-1]==' ') else start
            end = i if (i==len(s)-1 or s[i+1]==' ') else end

        if start != -1 and end != -1:
            reverse(s, start, end)
            start = -1
            end = -1

    return ''.join(s)

def reverse(s, start, end):
        """单词逆序
        """
    while start < end:
        s[start], s[end] = s[end], s[start]
        start += 1
        end -= 1
 

 

posted @ 2017-10-30 10:37  ML小菜鸟  阅读(985)  评论(0编辑  收藏  举报