151. 翻转字符串里的单词

类似的题目描述有将www.kuaishou.com转换为com.kuaishou.www

  • 1, 分割字符串
  • 2,反转字符串数组
  • 3,拼接字符串
  1. //分割+ 倒序合并字符串, 时空On
  2. func reverseWords(s string) string {
  3. var res []string
  4. list := strings.Split(s, " ") //1,以空格分开,待处理的串【】,成为数组模式
  5. for i := len(list) -1; i >= 0; i-- {
  6. if len(list[i]) > 0 { //去首尾空格,业务要求
  7. res = append(res, list[i]) //2,新的串res【】,数组模式
  8. }
  9. }
  10. s = strings.Join(res, " ") //3,合并,同时转换为串模式
  11. return s
  12. }
//双指针 时间On,空间O1
func reverseWords(s string) string {
    slowIndex, fastIndex := 0, 0        //1.使用双指针删除冗余的空格
    b := []byte(s)

    for len(b) > 0 && fastIndex < len(b) && b[fastIndex] == ' ' {
        fastIndex++                     //删除头部冗余空格
    }

    for ; fastIndex < len(b); fastIndex++ {
        if fastIndex-1 > 0 && b[fastIndex-1] == b[fastIndex] && b[fastIndex] == ' ' {
            continue                    //删除单词间冗余空格
        }
        b[slowIndex] = b[fastIndex]
        slowIndex++
    }

    if slowIndex-1 > 0 && b[slowIndex-1] == ' ' {
        b = b[:slowIndex-1]             //删除尾部冗余空格
    } else {
        b = b[:slowIndex]
    }

    reverse(&b, 0, len(b)-1)            //2.反转整个字符串

    i := 0
    for i < len(b) {                    //3.反转单个单词  i单词开始位置,j单词结束位置
        j := i
        for ; j < len(b) && b[j] != ' '; j++ {
        }
        reverse(&b, i, j-1)
        i = j
        i++
    }
    return string(b)
}

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