Golang算法 - Leetcode

 主页   资讯   文章   代码   电子书 

6. ZigZag Conversion

Leetcode 链接

题目

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 s, int numRows);

Example 1:

Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
Example 2:

Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:

P     I    N
A   L S  I G
Y A   H R
P     I

题意解析

Z 字型地读取字符串。

解决方案

这道题处理起来太绕了,我的解决方案是:

  • 1) 首先把字符串分组,例如 numRows = 3, 那么就以 3 列作为一组
  • 2) 接着把每一列作为一个数组,对数组赋值。最终形成一个二维数组。
  • 3) 最后按照行的顺序读出

Go 代码一

func convert(s string, numRows int) string {
    if s == "" || numRows==1{
        return s
    }

    // 分组
    group := numRows + (numRows - 2)

    col := (len(s) / group) * (numRows - 1)
    if len(s) % group != 0 {
        if len(s) % group - numRows > 0 {
            col += 1 + (len(s) % group - numRows)
        } else {
            col += 1
        }
    }

    arr := make([][]string, col)
    for i, _ := range arr {
        arr[i] = make([]string, numRows)
    }

    cnt := 0
    for c := 0; c < col; c++ {
        t := numRows - 1

        if  c % t == 0 {
            for row := 0; row < numRows && cnt<len(s); row++{
              arr[c][row] = string(s[cnt])
              cnt++
           }
        } else {
            arr[c][t - c%t] = string(s[cnt])
            cnt++
        }        
    }

    res := ""
    for i:=0; i<numRows; i++{
        for j:=0; j<col; j++{
            res += arr[j][i]
        }
    }

    return res
}