Skip to content

Instantly share code, notes, and snippets.

@phanngoc
Created September 29, 2018 09:09
Show Gist options
  • Save phanngoc/c2fc1ece3793574e9b1111d3a9bc52bf to your computer and use it in GitHub Desktop.
Save phanngoc/c2fc1ece3793574e9b1111d3a9bc52bf to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"strings"
)
func convert(s string, numRows int) string {
length := int(len(s))
if numRows == 1 {
return s
}
t := strings.Split(s, "")
res := make([]string, length)
numDiv := numRows - 1
i, j, y := 0, 0, 0
landmark := make([]int, 0)
belowLandmark := make([]int, 0)
isAbove := true
for i = 0; i <= length-1; i++ {
if i%numDiv == 0 {
if isAbove {
res[j] = t[i]
j++
landmark = append(landmark, i)
isAbove = false
} else {
belowLandmark = append(belowLandmark, i)
isAbove = true
}
}
}
maxRun := numRows - 1
k := 0
for i = 1; i <= maxRun; i++ {
for y = 0; y <= len(landmark)-1; y++ {
beforeIndex := landmark[y] - i
afterIndex := landmark[y] + i
if beforeIndex >= 0 && beforeIndex <= length-1 {
res[j] = t[beforeIndex]
j++
}
if k >= 0 && k <= int(len(belowLandmark))-1 && belowLandmark[k] == afterIndex {
k++
} else {
if afterIndex >= 0 && afterIndex <= length-1 {
res[j] = t[afterIndex]
j++
}
}
}
}
return strings.Join(res, "")
}
func main() {
s := "PAYPALISHIRING"
n := 3
res := convert(s, n)
fmt.Println("res:", res)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment