6.go 578 B

1234567891011121314151617181920212223242526272829
  1. package main
  2. func convert(s string, numRows int) string {
  3. n := len(s)
  4. if n < 3 || numRows == 1 {
  5. return s
  6. }
  7. cycle := numRows*2 - 2
  8. arr := make([][]rune, numRows)
  9. for i, v := range s {
  10. idx := i % cycle
  11. if idx < numRows {
  12. arr[idx] = append(arr[idx], v)
  13. } else {
  14. arr[(numRows-1)*2-idx] = append(arr[(numRows-1)*2-idx], v)
  15. }
  16. }
  17. res := make([]rune, 0)
  18. for _, v := range arr {
  19. res = append(res, v...)
  20. }
  21. return string(res)
  22. }
  23. /* func main() {
  24. fmt.Println(convert("PAYPALISHIRING", 3))
  25. fmt.Println(convert("ABCDE", 4))
  26. fmt.Println("PAHNAPLSIIGYIR")
  27. } */