题目描述
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:
string convert(string text, int nRows);
convert("PAYPALISHIRING", 3)should return"PAHNAPLSIIGYIR".
思路:
解:
String to Integer (atoi)
题目描述
思路:
- 行数为rows,周期为2*rows-2。
- 遍历字串,打印各周期:行数以内赋给各行,行数内对round-rows行字串赋值。
解:
package main
import "fmt"
func convert(s string, numRows int) string {
if numRows == 1{
return s
}
sSlice := []rune(s)
rows := make([]string,numRows)
for idx,_ := range rows{
rows[idx] = ""
}
round := 2*len(rows)-2
for i:=0;i<len(sSlice);i++{
rem := i%round
if rem< len(rows) {
rows[rem] += string(sSlice[i])
}else {
rows[round-rem] += string(sSlice[i])
}
}
res := ""
for _,elem := range rows{
res += elem
}
return res
}
func main() {
//s := "PAYPALISHIRING"
res := convert("A",2)
fmt.Print(res)
}
思路2:
- Z型串打印,可以非递归实现,不用“尾递归”。
- rowsIdx和strIdx递增打印。打印到rowsIdx==len(rows),再向上打印完这个周期(注意此过程打印完字串则程序结束)。
细节:
- 会用到HERE:跳转。
解:
import "fmt"
func convert(s string, numRows int) string {
if numRows == 1{
return s
}
sSlice := []rune(s)
rows := make([]string,numRows)
for idx,_ := range rows{
rows[idx] = ""
}
for i,ri:=0,0;i<len(sSlice);{
if ri == len(rows) {
for j := ri-2;j>0;j--{
rows[j] += string(sSlice[i])
i++
if i == len(sSlice){
goto HERE
}
}
ri = 0
}
rows[ri] += string(sSlice[i])
ri++
i++
}
HERE:
res := ""
for _,elem := range rows{
res += elem
}
return res
}
func main() {
s := "PAYPALISHIRING"
res := convert(s,3)
fmt.Print(res)
}