Golang Leetcode 6. ZigZag Conversion.go

2019-04-12 13:58:27 浏览数 (1)

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

思路

关键是要算出循环的长度:

为 row row -2

code

代码语言:javascript复制
func convert(s string, numRows int) string {
	if numRows == 1 {
		return s
	}

	item_len := 2*numRows - 2 //循环的长度
	res := make([][]string, numRows, numRows)

	for index, v := range s {

		mod := index % item_len

		if mod < numRows {
			res[mod] = append(res[mod], string(v))
		} else {
			i := numRows - (mod - numRows) - 2
			res[i] = append(res[i], string(v))
		}
	}

	var str string

	for _, arr := range res {
		for _, v := range arr {
			str  = v
		}
	}

	return str
}

0 人点赞