Leetcode: 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".

最简单的做法应该是申请一个二维组数,先按照规律填充好,然后再按行合并起来。进一步呢,可以用一些简单的公式直接填充结果字符串,一行行来,计算当前位置的字符在输入字符串的哪个位置。

class Solution {
public:
    string convert(string s, int nRows) {
        if (s.empty() || nRows <= 1) {
            return s;
        }
        
        // Calculate the maximum columns
        int size = s.size();
        string result(size, '\0');
        int step = nRows + nRows - 2;
        int column = size / step;
        if (size % step) {
            ++column;
        }
        
        int i = 0;
        for (int r = 0; r < nRows; ++r) {
            int index = r;
            int middle = 2 * (nRows - r - 1);
            for (int c = 0; c < column && index < size; ++c) {
                // Calcualte the indices to fill in the result
                result[i++] = s[index];
                if (r != 0 && r != nRows - 1) {
                    if (index + middle < size) {
                        result[i++] = s[index+middle];
                    }
                }
                index += step;
            }
        }
        
        return result;
    }
};

你可能感兴趣的:(LeetCode)