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 RAnd 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"
.
我的思路:
对于 numsRows > 2 的情况,找出原字符串和新字符串每个字符下标的对应关系。
P A H N A P L S I I G Y I R
如上图所示,对于原字符串中的每个元素,其在新字符串中的下标即为在他之前的元素数目 num,num 由两部分组成,一部分是该元素所在行之上所有行的元素数目,另一部分是该元素所在行中在该元素左边的元素数目。
具体实现如下:
char* convert(char* s, int numRows) {
int n = 0;
while(s[n] != '\0') n++;
if(numRows == 1 || n <= numRows) return s;
char* sn = (char*)malloc((n + 1) * sizeof(char));
sn[n] = '\0';
if(numRows == 2){
int rowLen = n / 2;
if(n % 2) rowLen += 1;
for(int i = 0;i < n;i++) sn[(i % 2) * rowLen + i / 2] = s[i];
return sn;
}
int* rowLens = (int*)malloc((numRows + 1) * sizeof(int));
rowLens[0] = 0;
int Len = n / (2*numRows - 2),tail = n % (2*numRows - 2);
rowLens[1] = Len,rowLens[numRows] = Len;
for(int i = 2;i < numRows;i++) rowLens[i] = 2*Len;
if(tail > 0){
for(int i = 1;i < tail + 1 && i <= numRows;i++) rowLens[i]++;
if(tail > numRows){
tail -= numRows;
for(int i = numRows - 1;tail > 0;i--){
rowLens[i]++;
tail--;
}
}
}
for(int i = 1;i <= numRows;i++) rowLens[i] += rowLens[i-1];
for(int i = 0;i < n;i++){
int unitIndex = i / (2*numRows - 2),InnerIndex = i % (2*numRows - 2);
if(0 < InnerIndex && InnerIndex + 1 < numRows) sn[rowLens[InnerIndex] + 2*unitIndex] = s[i];
else if(InnerIndex + 1 > numRows) sn[rowLens[numRows - (InnerIndex + 1 - numRows) - 1] + 2*unitIndex + 1] = s[i];
else sn[rowLens[InnerIndex] + unitIndex] = s[i];
}
return sn;
}
看了其他人的解法,发现自己写的太麻烦了。。其实直接用一个字符串数组去存储每一行的字符,最后一批一拼接就行了。还可以找规律,具体的在
这里。