Leetcode Golang 151. Reverse Words in a String.go

2019-04-12 10:47:35 浏览数 (1)

版权声明:原创勿转 https://cloud.tencent.com/developer/article/1412857

思路

就是简单的拆分,调换顺序,然后重组。

大神有更好的思路欢迎赐教

code

代码语言:javascript复制
func reverseWords(s string) string {
	arr := strings.Split(s, " ")
	res := []string{}
	for i := 0; i < len(arr); i   {
		if arr[i] != "" {
			res = append(res, arr[i])
		}
	}
	for i, j := 0, len(res)-1; i < j; i, j = i 1, j-1 {
		res[i], res[j] = res[j], res[i]
	}

	return strings.Replace(strings.Trim(fmt.Sprint(res), "[]"), " ", " ", -1)

}

0 人点赞