[leetcode题解]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 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

将字符串 “PAYPALISHIRING” 以Z字形排列成给定的行数:

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

之后从左往右,逐行读取字符:”PAHNAPLSIIGYIR”

实现一个将字符串进行指定行数变换的函数:

string convert(string s, int numRows);

示例 1:

输入: s = "PAYPALISHIRING", numRows = 3 输出: "PAHNAPLSIIGYIR"

示例 2:

输入: s = "PAYPALISHIRING", numRows = 4 输出: "PINALSIGYAHRPI" 解释: P     I    N
A   L S  I G
Y A   H R
P     I

纯模拟题,简单找一下规律就可以了,然后直接输出就行,代码如下:
char* convert(char* s, int numRows) {
    int len = strlen(s);
    char *sres = calloc(1, len + 1);
    int i = 0;
    int j = 0;
    int pos = 0;
    int gap = (numRows - 1) * 2;
    int step = 0;
    
    if (numRows <= 1)
        return s;
    
    for (i = 0; i < numRows; i++) {
        step = 2 * (numRows - i % (numRows - 1) - 1);
        for (j = i; j < len;) {
            sres[pos++] = s[j];
            j += step;
            step = gap - step;
            if (step == 0)
                step = gap - step;
        }
    }
    
    return sres;
}

本文遵从CC3.0协议转载请注明:转自凌风技术站

本文标题:[leetcode题解]6. ZigZag Conversion

本文链接地址:http://www.iaccepted.net/algorithm/leetcode/180.html

相关文章