將一個給定字符串根據給定的行數,以從上往下、從左到右進行 Z 字形排列。
比如輸入字符串爲 "LEETCODEISHIRING"
行數爲 3 時,排列如下:
L C I R E T O E S I I G E D H N
之後,你的輸出需要從左往右逐行讀取,產生出一個新的字符串,比如:"LCIRETOESIIGEDHN"
。
請你實現這個將字符串進行指定行數變換的函數:
string convert(string s, int numRows);
示例 1:
輸入: s = "LEETCODEISHIRING", numRows = 3 輸出: "LCIRETOESIIGEDHN"
示例 2:
輸入: s = "LEETCODEISHIRING", numRows = 4 輸出: "LDREOEIIECIHNTSG" 解釋: L D R E O E I I E C I H N T S G
char* convert(char* s, int numRows) {
int n = numRows, index = 0;
int len = strlen(s), temp = 0;
int i = 0, t = 2 * n - 2;
char* result = (char*)malloc((len + 1) * sizeof(char));
result[len] = '\0';
if((n == 1)||(len <= n)) {
memcpy(result, s, len * sizeof(char));
return result;
}
for(i = 0; i < n; i++) {
result[index++] = s[i];
temp = i;
while(1) {
if(t - 2 * i) {
if(temp + t - 2 * i < len) {
temp += (t - 2 * i);
result[index++] = s[temp];
}
else
break;
}
if(2 * i) {
if(temp + 2 * i < len) {
temp += 2 * i;
result[index++] = s[temp];
}
else
break;
}
}
}
return result;
}