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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/zigzag-conversion
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>


char *convert(char *s, int numRows)
{
    int i = 0, j = 0, k = 0;
    int len = strlen(s);
    int index = 0;
    char *dst = (char *)malloc(sizeof(char) * (len + 1));
    int n = 2*numRows-2;

    if (numRows <= 1)
    {
        return s;
    }

    for (i = 0; i < numRows; i++)
    {
        for (j = 0; j < len; j++)
        {
            k = j%n;
            if ((k == i)||(k == n-i))
            {
                dst[index++]=s[j];
            }
        }
    }
    dst[index] = '\0';

    return dst;
}

int main()
{
    char *s="LEETCODEISHIRING";
    int len = strlen(s) + 1;
    char *d = (char *)malloc(sizeof(char)*len);

    memset(d, '\0', len);

    d = convert(s,3);
    printf("After Z convert the string is %s\n", d);

    d = convert(s,4);
    printf("After Z convert the string is %s\n", d);

}

output

weihanwu@weihanwu-OptiPlex-990:~/work/code_exec/C_exec$ ./a.out 
After Z convert the string is LCIRETOESIIGEDHN
After Z convert the string is LDREOEIIECIHNTSG
weihanwu@weihanwu-OptiPlex-990:~/work/code_exec/C_exec$
发布了223 篇原创文章 · 获赞 160 · 访问量 20万+

猜你喜欢

转载自blog.csdn.net/u014100559/article/details/101072234
今日推荐