字符串 01

yuhao0451 / 2023-08-27 / 原文

def removeSpaces(s) :
    left, right = 0, len(s)- 1
    #去除开头的空格
    while left < right and s[left] == ' ' :
        left += 1
    while left < right and s[right] == ' ' :
        right -= 1 

    new_s = [] 
    while left <= right :
        if s[left] != ' ' :
            new_s.append(s[left]) 
            #new_s[-1] 为new_s 最后一个字符
            #如果这个字符不是空格,则继续添加
        elif s[left] == ' ' and new_s[-1] != ' ' :
            new_s.append(s[left]) 
        left += 1
    return new_s     

def reverseString(s) :
    left, right = 0, len(s) - 1
    while left < right :
        s[left], s[right] = s[right], s[left] 
        left += 1 
        right -= 1 
    
    return s 

def reverseEachWord(s) :
    left, right = 0, 0 
    n = len(s) 

    while left < n :
        while right < n and s[right] != ' ' :
            right += 1
        s[left:right] = reverseString(s[left:right]) 
        left = right + 1
        right += 1
    
    return s 

def reverseWords(s) :
    s = removeSpaces(s) 
    s = reverseString(s) 
    s = reverseEachWord(s) 
    return ''.join(s)

leetcode: 151

 

相关阅读:https://leetcode.cn/problems/reverse-words-in-a-string/solutions/1167554/acm-xuan-shou-tu-jie-leetcode-fan-zhuan-moi5x/