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

题意

将字符串按zigzag型排序,再从第一行至第N行从左至右输出。

思路

只要找到规律就很简单,以下是自己画的简易图。。。

row代表行号。

1.row=0或者n-1时,每一列只需要输出一个数就行。例如当row=0,0列输出0,第1列输出2(n-1),以此类推。

2.0<row<n-1时,除了第0列只输出一个数,其他列输出两个数。如row=1时,第0列输出1,第1列输出2(n-1)-1 2(n-1)+1.

 

 1 char* convert(char* s, int numRows) { //numRows代表要将字符串转换成numRows行的第zigzag型
 2     size_t len=strlen(s);
 3     char *ans;
 4     ans=(char*)malloc(sizeof(char)*25000);
 5     int j=0;
 6     if(numRows==1) return s;
 7     else
 8     for(int row=0;row<numRows;row++)
 9     {
10         int index=2*numRows-2;
11         int i=0; //i代表第i列
12         if (row==0 || row==numRows-1)
13         {
14             while(i*index<len)
15             {
16                 ans[j++]=s[i*index+row];
17                 i++;
18             }
19         }
20         else
21         {
22             while(i*index+row<len || i*index-row<len)
23             {
24                 if(i*index-row<len && i*index-row>=0)
25                     ans[j++]=s[i*index-row];
26                 if(i*index+row<len)
27                     ans[j++]=s[i*index+row];
28                 i++;
29             }
30         }
31     }
32     ans[len]='\0';
33     return ans;
34 }
View Code

 

posted @ 2015-07-19 13:12  Mad.King  阅读(178)  评论(0编辑  收藏  举报