首页 > 代码库 > [LeetCode]6.ZigZag Conversion

[LeetCode]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"

这个题主要是在找规律,一开始写的时候中了c数组的陷阱,面试题切记

要注意的就是在C语言中,不推荐函数内的局部变量地址返回到函数外,局部变量的生命周期到返回就已经结束,数组在栈上的地址已经释放

但是可以返回静态开辟的数组(静态区在程序结束时才释放),或者把外部建立的数组传递进函数。

或者

使用动态开辟的空间(但是动态开辟要求谁申请谁释放,否则容易内存溢出,建议在函数外部开辟,并在返回后使用完毕释放)
char* str;
str=(char*)malloc(sizeof(char)*(n+1));
str[n]=‘\0‘

或者

还是用局部变量数组,返回时把临时数组的值给到传入的字符串s上

memcpy(s,result,sizeof(char)*strlen(s));

 1 char* convert(char* s, int numRows) {
 2     int len = strlen(s);
 3     int row, i, j, step, tmp;
 4     static char result[1000];
 5     result[len] = \0;
 6     
 7     
 8     if(numRows <= 1 || len <= numRows)
 9         return s;
10     
11     step = (numRows - 1) * 2;
12     
13     for(j=row = 0; row < numRows; row++){
14         tmp = (numRows - row - 1) * 2;
15         for(i = row; i < len; i+=step)
16         {
17             result[j++] = s[i];
18             if(row > 0 && row < numRows -1 && i + tmp < len)
19             {
20                 result[j++] = s[i+tmp];
21             }
22         }
23     }
24     
25     return result;
26 }

 

[LeetCode]6.ZigZag Conversion