首页 > 编程语言 > 详细

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

时间:2017-10-30 13:27:57      阅读:290      评论:0      收藏:0      [点我收藏+]

题目描述:试实现一个函数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
 

 

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

原文:http://www.cnblogs.com/lianyingteng/p/7753465.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!