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 text, int nRows);

convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR"

思考过程:以题目所举例子为例,第一个字符放在第一行,第二个放在第二行,...。这一个过程是以4为一个循环,那么能否对字符串中的任意个字符预先判断出其所在的行数呢,通过小例子的演算,发现,字符的下标对4取余,即可知道其所在的行数。据此实现程序。

 1 char* convert(char* s, int numRows) {
 2     if(!strlen(s)) return s;
 3     
 4     if(numRows==1) return s;
 5     
 6     int len = strlen(s);
 7     char *s2 = malloc(sizeof(char) * (len+1));
 8     memset(s2, 0, sizeof(s2));
 9 
10     int count = 0;
11     
12     int loop = numRows + (numRows -2);
13     for(int i= 0; i<numRows; i++) {
14         for(int j = 0; j<len; j++){
15             if(j%loop==i || j%loop==loop-i){
16                 s2[count]=s[j];
17                 count++;
18             }
19         }
20     }
21     
22     s2[count]='';
23     
24     return s2;
25 }
原文地址:https://www.cnblogs.com/midhillzhou/p/8693437.html