Leetcode专题[字符串]-151-翻转字符串里的单词

力扣链接:
https://leetcode-cn.com/probl...
解题思路:

  1. 这道题如果单独开辟空间,比较好解
  2. 如果原地进行实现,那么就比较有难度,需要技巧,这里使用双指针的解法,先去除冗余空格
  3. 然后进行两次翻转,首先全字符串翻转,然后针对单词翻转,翻转的翻转就是原文
func reverseWords(s string) string {
    b := []byte(s)
    // 核心解法:两次翻转,首先进行整体的翻转,然后单词翻转复位,可以实现原地操作
    // 1、定义快慢指针,进行去处多余空格的操作
    fastIndex, slowIndex := 0, 0
    // 2、首先移除字符串首部的空格
    for len(b) > 0 && fastIndex < len(b) && b[fastIndex] == ' ' {
        fastIndex++
    }
    // 3、移除字符串中间的冗余空格
    for ; fastIndex < len(b); fastIndex++ {
        if fastIndex - 1 > 0 && b[fastIndex - 1] == b[fastIndex] && b[fastIndex] == ' ' {
            continue
        }
        b[slowIndex] = b[fastIndex]
        slowIndex++
    }
    // 4、移除字符串末端的冗余空格
    if slowIndex > 0 && b[slowIndex-1] == ' ' {
        b = b[:slowIndex - 1]
    } else {
        b = b[:slowIndex]
    }
    // 5、整体翻转
    reverse(&b, 0, len(b)-1)
    // 6、遍历分单词翻转
    i := 0
    for i < len(b) {
        j := i
        for ; j < len(b) && b[j] != ' '; j++ {
        }
        reverse(&b, i, j-1)
        i = j
        i++
    }
    return string(b)
}

func reverse(b *[]byte, low, high int) {
    for low <= high {
        (*b)[low], (*b)[high] = (*b)[high], (*b)[low]
        low++
        high--
    }
}

你可能感兴趣的:(golang)