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

 

相关文章:

  • 2021-11-01
  • 2021-08-31
  • 2022-12-23
  • 2021-12-09
  • 2022-12-23
  • 2022-01-16
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-08-08
  • 2021-07-21
  • 2021-11-14
  • 2022-03-10
  • 2021-08-02
  • 2022-01-28
相关资源
相似解决方案