「每日一道算法题」ZigZag Conversion

Algorithm

OJ address

Leetcode website : 6. ZigZag Conversion

Description

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

Solution in C

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

char* convert(char* s, int numRows) {
    int length = strlen(s);
    if (length <= 1) return s;
    if (numRows == 1) return s;
    char *a = malloc(sizeof(char)*(length+1));
    int lenarray[numRows];
    int leng = length-1;
    int yushu = leng%(2*numRows-2);
    lenarray[0] = (leng - leng%(2*numRows-2))/(2*numRows-2)+1;
    int total = lenarray[0];
    for (int i=1;i<numRows-1;++i) {
        int flag = 0;
        if (yushu >= i) flag = 1;
        if (yushu >= 2*numRows-2-i) flag = 2;
        lenarray[i] = (lenarray[0]-1)*2 + flag;
        total += lenarray[i];
        lenarray[i] = total;
    }
    for (int i=0,j=0;s[i]!='\0';++i) {
        if (i % (2*numRows-2) == 0) {
            a[i/(2*numRows-2)] = s[i];
        }
        else if (i % (2*numRows-2) == numRows-1) {
            a[total+(i-(numRows-1))/(2*numRows-2)] = s[i];
        }
        else {
            int yushu = i%(2*numRows-2);
            int cengci = (i - i%(2*numRows-2))/(2*numRows-2);
            int row = 0;
            if (yushu < numRows-1) {
                row = yushu;
                a[lenarray[row-1]-1+cengci*2+1] = s[i];
            }
            else {
                row = 2*numRows-2-yushu;
                a[lenarray[row-1]-1+cengci*2+2] = s[i];
            }
        }
    }
    a[length] = '\0';
    return a;
}

int main(int argc, char const *argv[])
{
    char *s = "PAYPALISHIRING\0";
    //char *s = "AB\0";
    char *p = convert(s, 1);
    printf("%s\n", p);
    return 0;
}

My Idea

题目含义是,以给定字符串写成如下Z形模式打印出来。

没有看网上的解题方法,按照自己的方式做出来,速度大概是:

Runtime: 12 ms, faster than 100% of C online submissions for ZigZag Conversion.

这个数据不太准,第二次提交,就变成了16ms.但是的确是O(n)的方式解决。

我的方法比网上的解答方法要复杂很多,我是求出了每行的个数,然后根据自己求出的规律,对每个元素的位置进行规律求解,然后进行赋值。

举例来说第三行就是前两行的所有字母的总和加上这个字母在第三行的位置。对我就是用了这样笨的算法。活生生的变成了数学题。难度直线上升啊。

猜你喜欢

转载自blog.csdn.net/weixin_34194379/article/details/86954572