zoukankan      html  css  js  c++  java
  • LintCode翻转字符串问题

    题目描述:试实现一个函数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
     
  • 相关阅读:
    TcpUDP通讯
    hashlib模块和logging模块
    Windows之系统自带截屏快捷键
    Windows之文件夹中打开PowerShell
    scrapy之管道
    爬虫之通讯协议
    爬虫
    jupyter使用
    MongoDB之$
    MongoDB之修改器
  • 原文地址:https://www.cnblogs.com/lianyingteng/p/7753465.html
Copyright © 2011-2022 走看看