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
52
53

#include <string>
#include <iostream>

using namespace std;

string Convert(string s, int nRows) 
{
    if (nRows < 2)return s;

    int pattenSize = (nRows-1)*2;
    int length = s.size();
    string r; //result;
    //first row
    for (int i = 0; i < length; i += pattenSize)
        r.push_back(s[i]);

    //each row except first and last would contains two letters in one pattern
    for (int i = 1; i < nRows-1; ++i)
    {
        for (int j = i; j < length; j += pattenSize)
        {
            r.push_back(s[j]);
            int k = (j-i) + (pattenSize - i);
            if (k < length)r.push_back(s[k]);
        }
    }

    //Last row
    for (int i = nRows-1; i < length; i += pattenSize)
        r.push_back(s[i]);

    return r;
}


int main(int argc, char** argv)
{
    string s = "PAYPALISHIRING";
    cout << Convert(s, 3) << endl;
    cout << Convert(s, 4) << endl;
    cout << Convert(s, 5) << endl;
	
    s = "jieghdncltrryzfm";
    cout << Convert(s, 10) << endl;  
	
	/*
PAHNAPLSIIGYIR
PINALSIGYAHRPI
PHASIYIRPLIGAN
jiegmhfdznycrlrt
*/
return 0; }
View Program Text


Test Status