Loading

151.翻转字符串里的单词

151.翻转字符串里的单词

力扣题目链接(opens new window)

给定一个字符串,逐个翻转字符串中的每个单词。

示例 1:
输入: "the sky is blue"
输出: "blue is sky the"

示例 2:
输入: " hello world! "
输出: "world! hello"
解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。

示例 3:
输入: "a good example"
输出: "example good a"
解释: 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。

func reverseWords(s string) string {
    b:=[]byte(s)
    length:=len(b)
    slow:=0
    for fast:=0;fast<length;fast++{
        if b[fast]!=' '{
            if slow!=0 {
                b[slow]=' '
                slow++
            }
            for (fast<length)&&(s[fast]!=' '){
                b[slow]=b[fast]
                slow++
                fast++
            }
        }
    }
    b=b[:slow]
    reverse(&b,0,slow-1)
    start:=0
    for i:=0;i<=slow;i++{
        if (i==slow)||(b[i]==' '){
            reverse(&b,start,i-1)
            start=i+1
        }
    }
    return string(b)
}


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

posted @ 2022-12-06 15:28  suehoo  阅读(35)  评论(0)    收藏  举报