The string “PAYPALISHIRING” is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: “PAHNAPLSIIGYIR”
Write the code that will take a string and make this conversion given a number of rows:
func convert(text string, nRows int) string
convert(“PAYPALISHIRING”, 3) should return “PAHNAPLSIIGYIR”.
解题思路
- 按图找规律(类似等差数列)
func convert(text string, nRows int) string {
var result string
if nRows == 1 {
return text
}
p := 2*nRows - 2
length := len(text)
for i := 0; i < nRows; i++ {
// 首/尾特殊处理
if i == 0 || i == nRows-1 {
for j := 0; ; j++ {
if i+j*p < length {
result += string(text[i+j*p ])
} else {
break
}
}
} else {
// 其他行,奇偶判断,分别处理
first := i
second := i + (p - 2*i)
if first < length {
result += string(text[first])
} else {
continue
}
if second < length {
result += string(text[second])
} else {
continue
}
for j := 1; ; j++ {
if first+j*p < length {
result += string(text[first+j*p])
} else {
break
}
if second+j*p < length {
result += string(text[second+j*p])
} else {
break
}
}
}
}
return result
}