6. ZigZag Conversion

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”.

// author liyiheng
func convert(s string, numRows int) string {
    if numRows==1 {
        return s
    }
    nos :=strings.Split(s,"")
    grid := make([][]string, numRows)

    cnt := len(nos) / (numRows * 2 - 2)
    column := cnt * (numRows - 1)
    ret := len(nos) % (numRows * 2 - 2)
    if ret <= numRows {
        column++
    } else {
        ret -= numRows
        column++
        column += ret
    }
    for i := 0; i < numRows; i++ {
        grid[i] = make([]string, column)
    }
    x, y := 0, 0
    down := true
    for _, v := range nos {
        // row-1 的整數倍爲整列
        grid[x][y] = v
        if down {
            x++
            if x == numRows-1 {
                down = false
            }
        } else {
            x--
            y++
            if x == 0 {
                down = true
            }
        }
    }
    result := ""
    for _, slc := range grid {
        for _, v := range slc {
            if v != "" {
                result +=v
            }
        }
    }
    return result
}
發佈了21 篇原創文章 · 獲贊 5 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章