1
1
/*
2
+ * The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this:
3
+ * (you may want to display this pattern in a fixed font for better legibility)
4
+ *
5
+ * P A H N
6
+ * A P L S I I G
7
+ * Y I R
8
+ *
9
+ * convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".
10
+ *
2
11
* Created by supercoderhawk on 2017/7/24.
3
12
*/
13
+ #include
14
+ #include
15
+ #include
4
16
17
+ char * convert (char * s , int numRows ) {
18
+ if (numRows == 1 )
19
+ return s ;
20
+
21
+ char * p = s ;
22
+ int length = 0 , index = 0 ;
23
+ while (* p != '\0' ) {
24
+ length ++ ;
25
+ p ++ ;
26
+ }
27
+
28
+ char * zigzag = (char * ) malloc (sizeof (char ) * (length + 1 ));
29
+ char * * table = (char * * ) malloc (sizeof (char * ) * numRows );
30
+ int tableIndex [numRows ];
31
+ for (int i = 0 ; i < numRows ; i ++ ) {
32
+ table [i ] = (char * ) malloc (sizeof (char ) * (length /2 + 1 ));
33
+ tableIndex [i ] = 0 ;
34
+ }
35
+
36
+ index = 0 ;
37
+ while (index < length ) {
38
+ for (int i = 0 ; i < numRows && index < length ; i ++ )
39
+ table [i ][tableIndex [i ]++ ] = s [index ++ ];
40
+ for (int i = numRows - 2 ; i > 0 && index < length ; i -- )
41
+ table [i ][tableIndex [i ]++ ] = s [index ++ ];
42
+ }
43
+
44
+ index = 0 ;
45
+
46
+ for (int i = 0 ; i < numRows ; i ++ ) {
47
+ strncpy (zigzag + index , table [i ], tableIndex [i ]);
48
+ index += tableIndex [i ];
49
+ }
50
+ zigzag [index ] = '\0' ;
51
+ return zigzag ;
52
+ }
53
+
54
+ void testConvert () {
55
+ char * p1 = "nhlvnsnklobqkfoifwsdzfgoueicotgearzqloawcbomgcwnyosztzoqdyutrbxsuzignicqkresvbgwravnzjdek" ;
56
+ char * p2 = "PAHNAPLSIIGYIR" ;
57
+ int res = strcmp (convert (p1 , 41 ), p2 );
58
+ printf ("%d\n" , res );
59
+
60
+ char * p21 = "Apalindromeisaword,phrase,number,orothersequenceofunitsthatcanbereadthesamewayineitherdirection,withgeneralallowancesforadjustmentstopunctuationandworddividers." ;
61
+ char * p22 = "Aiosrhem,tseoihartaaeeriwgrlasasnoctaoieplnrmiaodprs,ubroohreunefnttacneedhsmwynihrieto,iheeaalwnefrdutettpntainnwrdvdr.adew,anereqcustbaeeitdcntnlocojmsuuoddis" ;
62
+ int res2 = strcmp (convert (p21 , 3 ), p22 );
63
+ printf ("%d\n" , res2 );
64
+ }
0 commit comments