6.go 591 B

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