# (六) ZigZag Convert

L白水飘萍 · · 640 次点击 · · 开始浏览

### 题目

``````L   C   I   R
E T O E S I I G
E   D   H   N
``````

``````string convert(string s, int numRows);
``````

``````输入: s = "LEETCODEISHIRING", numRows = 3

``````

``````输入: s = "LEETCODEISHIRING", numRows = 4

L     D     R
E   O E   I I
E C   I H   N
T     S     G
``````

### 解答

``````ABCDEFGHIJKLMNOPQ 4
A    H    N
B  G I  M O
C F  J L  P
D    K    Q
``````

#### C语言

``````char* convert(char* s, int numRows) {
if(s  == NULL || numRows < 1)
return s;
int len = strlen(s);
if(len == 0)
return s;

char *res = (char *)malloc(sizeof(char)*(len+1));
res[len] = '\0';

if(numRows == 1)
{
strcpy(res,s);
return res;
}

int m = 0;
int inter1 = 2 * numRows -2;
for(int i = 0;i < numRows;i++){
if(i == 0 || i== numRows-1){
for(int j = i;j < len;j += inter1)
res[m++] = s[j];
}else{
int inter2 = 2 * i;
for(int j = i;j < len;j+=inter2){
res[m++] = s[j];
inter2 = inter1-inter2;
}
}
}
return res;
}
``````

#### Golang

``````func convert(s string, numRows int) string {
if len(s) <= 1 || numRows == 1 {
return s
}

res := make([]byte, len(s))
inter1 := 2*numRows - 2
m := 0
for i := 0; i < numRows; i++ {
inter2 := 2 * i
for j := i; j < len(s); j += inter2 {
res[m] = s[j]
m++
if i == 0 || i == numRows-1 {
inter2 = inter1
} else {
inter2 = inter1 - inter2
}
}
}
return string(res)
}

``````

0 回复

• 请尽量让自己的回复能够对别人有帮助
• 支持 Markdown 格式, **粗体**、~~删除线~~、``单行代码``
• 支持 @ 本站用户；支持表情（输入 : 提示），见 Emoji cheat sheet
• 图片支持拖拽、截图粘贴等方式上传

### 题目

``````L   C   I   R
E T O E S I I G
E   D   H   N
``````

``````string convert(string s, int numRows);
``````

``````输入: s = "LEETCODEISHIRING", numRows = 3

``````

``````输入: s = "LEETCODEISHIRING", numRows = 4

L     D     R
E   O E   I I
E C   I H   N
T     S     G
``````

### 解答

``````ABCDEFGHIJKLMNOPQ 4
A    H    N
B  G I  M O
C F  J L  P
D    K    Q
``````

#### C语言

``````char* convert(char* s, int numRows) {
if(s  == NULL || numRows < 1)
return s;
int len = strlen(s);
if(len == 0)
return s;

char *res = (char *)malloc(sizeof(char)*(len+1));
res[len] = '\0';

if(numRows == 1)
{
strcpy(res,s);
return res;
}

int m = 0;
int inter1 = 2 * numRows -2;
for(int i = 0;i < numRows;i++){
if(i == 0 || i== numRows-1){
for(int j = i;j < len;j += inter1)
res[m++] = s[j];
}else{
int inter2 = 2 * i;
for(int j = i;j < len;j+=inter2){
res[m++] = s[j];
inter2 = inter1-inter2;
}
}
}
return res;
}
``````

#### Golang

``````func convert(s string, numRows int) string {
if len(s) <= 1 || numRows == 1 {
return s
}

res := make([]byte, len(s))
inter1 := 2*numRows - 2
m := 0
for i := 0; i < numRows; i++ {
inter2 := 2 * i
for j := i; j < len(s); j += inter2 {
res[m] = s[j]
m++
if i == 0 || i == numRows-1 {
inter2 = inter1
} else {
inter2 = inter1 - inter2
}
}
}
return string(res)
}

``````