6. N 字形变换
为保证权益,题目请参考 6. N 字形变换(From LeetCode).
解决方案1
CPP
C++
#include <iostream>
#include <string>
using namespace std;
class Solution
{
public:
string convert(string s, int numRows)
{
if(s.length() == 1)
return s;
string res = "";
int n = numRows * 2 - 2;
for (int i = 0; i < numRows; ++i)
{
int index = i;
bool flag = true; // 用来标记是不是N的左部分
while (index < s.length())
{
res += s[index];
if (i == 0 || i == numRows - 1)
{
index += n;
}
else
{
if (flag)
{
index += n - 2 * i;
flag = false;
}
else
{
index += 2 * i;
flag = true;
}
}
}
}
return res;
}
};
int main()
{
Solution so;
cout << so.convert("A", 1) << endl;
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51