ZigZag Conversion

题目(ZigZag Conversion )--Medium

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


C语言解答

char* convert(char* s, int numRows) {
     int i,x,y;
     int length = strlen(s);
     int zigZagNum = numRows+numRows-2;//一个循环有多少个字符
     int zigZagSum;                    //需要多少个循环才能放下所有的字符
     int numCol;                       //列数
     char* result;                     
     char** charactors;               //存放字符串的二维数组
     if(numRows == 1||length == 0||length == 1||length == 2){
         return s;
     }
     if(length%zigZagNum == 0){
         zigZagSum = length/zigZagNum;
     }else{
         zigZagSum = length/zigZagNum + 1;
     }
     numCol = zigZagSum*(numRows - 1);   
     result = (char*)malloc(sizeof(char)*(length+1));
     
     charactors = (char**)malloc(sizeof(char*)*numRows);
     for(i = 0; i < numRows; i++){
         charactors[i] = (char*)malloc(sizeof(char)*numCol);
         memset(charactors[i],'\0',sizeof(char)*numCol);
     }
     //下面的for循环是把s中的字符按照ZigZag规则放到charactors中的核心代码
     for(i = 0; i < length; i++){
         if((i % zigZagNum) > numRows -1){
             x = 2*(numRows-1)-(i % zigZagNum);
             y = (i/zigZagNum)*(numRows - 1) + ((i%zigZagNum)-(numRows - 1)) ;
         }else{
             x = i%zigZagNum;
             y = i/zigZagNum*(numRows - 1);
         }
         charactors[x][y] = s[i];
     }
     i = 0;
     //下面的for循环是按照ZigZag输出规则,给result赋值
     for(x = 0; x < numRows; x++){
         for(y = 0; y < numCol; y++){
             if(charactors[x][y] != '\0'){
                 result[i] = charactors[x][y];
                 i++;
             }
         }
     }
     result[length] = '\0';
     return result;
}



收获

1.  首先要理解ZigZag的含义,单单通过题目的示例不足以确定ZigZag规则,所以首先英语单词得认识,zigzag: 锯齿形的线条。这样就能理解题意了(骗谁呢?实话是说,我也是百度了别人的解释之后才确定的),如下图所示:
ZigZag Conversion_第1张图片
2. 和大家用的方法不太一样,虽然原理都是找到规则的规律并模型化,我的想法是构造一个二维数组来解决问题,代码很简单,也就不详述了;而看了好多别人的解答,都是直接找到规律,然后在s数组中直接处理的,表示非常看不懂啊,好复杂。

你可能感兴趣的:(LeetCode)