leetcode系列(25)ZigZag Conversion 锯形转化

来源:互联网 发布:淘宝学习网站 编辑:程序博客网 时间:2024/04/28 06:06

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   NA P L S I I GY   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".

构造一个二维字符数组(vector<string>),按照zigzag的方式填充,就是拼接数组的每行字符串,输出就是了。填充过程中,

按列填充,第一列从第一行填充到最后一行,第二列则从最后一行填充到第一行,如此反复,直至填充完毕。


C++代码

class Solution {public:    string convert(string s, int numRows) {        vector<string> ret(numRows, string(""));        int cur_row = 0;        int step = 1;                if (numRows <= 1 || numRows >= s.size()) {            return s;        }                for (int i = 0; i < s.size(); ++i) {            ret[cur_row].push_back(s[i]);                        if (cur_row == 0) {                step = 1;            }                    if (cur_row == (numRows - 1)) {                step = -1;            }                        cur_row += step;        }                string zig_string("");        for (auto item = ret.begin(); item != ret.end(); ++item) {            zig_string += (*item);        }        return zig_string;    }};


Python代码

class Solution:    # @param {string} s    # @param {integer} numRows    # @return {string}    def convert(self, s, numRows):        if numRows <= 1 or numRows >= len(s):            return s                    ret = [""] * numRows        cur_row = 0        step = 1                for i in range(0, len(s)):            ret[cur_row] += s[i]                        if cur_row == 0:                step = 1                        if cur_row == (numRows - 1):                step = -1                        cur_row += step                zig_string = ""        for item in ret:            zig_string += item                return zig_string



0 0