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

char* convert(char* s, int n) {
    if(n==1) return s;
    int l=strlen(s),i,k;
    char *t=(char*)malloc(sizeof(char)*(l+1));
    if(t==NULL) puts("Mem error!");
    t[l]='\0';
    for(i=0;(i)*(n+n-2)<l;i++){
        t[i]=s[(i)*(n+n-2)];
    }
    k=i;
    for(int r=1;r<n-1;r++){
        t[i]=s[r];i++;
        for(int j=1;j<=k;j++){
            if(j*(n+n-2)-r<l){
                t[i]=s[j*(n+n-2)-r]; i++;
            }
            if(j*(n+n-2)+r<l){
               t[i]=s[j*(n+n-2)+r];i++;
            }
        }
    }
    for(int j=0; j<=k&&j*(n+n-2)+n-1<l;j++){
        t[i++]=s[j*(n+n-2)+n-1];
    }
    return t;
}

 

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据