[LeetCode]7. ZigZag Conversion ZigZag转换

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

解法:字符串 “0123456789ABCDEF”,转为zigzag:

n=2时,字符串坐标变成zigzag的走法就是:

 0 2 4 6

 1 3 5 7

 n=3时的走法是:

 0     4     8

 1  3 5  7 9

 2     6    10 

 n=4时的走法是:

 0      6        12

 1   5 7    11 13

 2 4   8 10    14

 3      9         15 

除了第一行和最后一行没有中间形成之字型的数字外,其他都有,而首尾两行中相邻两个元素的index之差跟行数是相关的,为 2*nRows - 2, 根据这个特点,我们可以按顺序找到所有的黑色元素在元字符串的位置,将他们按顺序加到新字符串里面。对于红色元素出现的位置也是有规律的,每个红色元素的位置为 j + 2*nRows-2 - 2*i, 其中,j为前一个黑色元素的列数,i为当前行数。 比如当n = 4中的那个红色5,它的位置为 1 + 2*4-2 - 2*1 = 5,为原字符串的正确位置。当我们知道所有黑色元素和红色元素位置的正确算法,我们就可以一次性的把它们按顺序都加到新的字符串里面。

class Solution {
public:
    string convert(string s, int numRows) {
        int ss = s.size();
        if (ss < 2 || numRows < 2 || ss < numRows)
            return s;

        string res("");
        int step = 2 * (numRows - 1);
        for (int i = 0; i < numRows; i++)
        {
            for (int j = i; j < ss; j += step)
            {
                res += s[j];
                int more = j + step - 2 * i;
                if (i != 0 && i != numRows - 1 && more < ss)
                    res += s[more];
            }
        }

        return res;
    }
};

参考:http://www.cnblogs.com/grandyang/p/4128268.html

原文地址:https://www.cnblogs.com/aprilcheny/p/4852854.html