首页 > 代码库 > ZigZag Conversion

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 text, int nRows);
convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".


#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char *convert(char *s, int nRows){
    int i,j,k=0;
    int len=strlen(s);
    char *p=(char *)malloc(sizeof(char)*len);
    int pos;
    if(nRows==1) return s;
    for(i=0; i<len && i<nRows; i++){
        for(j=0;j<len;j++){
            if(i==0 || i==nRows-1)
                pos=(nRows*2-2)*j+i;
            else{
                if((j+1)%2==0)
                   pos=(nRows*2-2)*(j-1)/2+(nRows*2-2-i);
                else
                   pos=(nRows*2-2)*j/2+i;
            }
            if(pos>=len) {
                break;
            }
            else {
                p[k]=s[pos];
                printf("ll:%d,%c\n",pos,p[k]);
                k++;
            }
        }
    }
    return p;
}

void main(){
    printf("%s\n",convert("P",1));
}


ZigZag Conversion