6. ZigZag Conversion

来源:互联网 发布:淘宝模特招聘是真的吗 编辑:程序博客网 时间:2024/06/02 06:30

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 R
And 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”.

int main(){    string s;    int nrow;    while (cin >> s >> nrow)    {        char imap[1000][1000];  //数组大小尝试出来的        memset(imap, 0, sizeof(imap));        int pos = 0;        int i = 0;        while (pos < s.size())          {            if (i % 2 == 0)   //列为偶数时            {                for (int k = 0; k < nrow && s[pos]!='\0'; k++) //注意添加的时候,要判断s[pos]!='\0' ,如果等于的话,则也跳出了循环,因为pos此时等于s.size()了                {                    imap[k][i] = s[pos++];                }            }            else  //列为奇数时            {                if(s[pos] != '\0') //判断s[pos]!='\0'                {                    if (nrow == 1) //nrow == 1另外考虑 ABCD 1 --> ABCD                        imap[0][i] = s[pos++];                    else if (nrow == 2) //nrow == 2另外考虑  ABCD 2 -->ACBD                        for (int k = 0; k < nrow && s[pos] != '\0'; k++)                        {                            imap[k][i] = s[pos++];                        }                    else  //nrow > 2, 从nrow - 2由下往上排                        for (int k = nrow - 2; k >= 1 && s[pos] != '\0'; k--)                        {                            imap[k][i] = s[pos++];                        }                }            }            i++;        }        s.clear();        for (int r = 0; r < nrow; r++)            for (int c = 0; c < i; c++)            {                if (imap[r][c] != 0)s.push_back(imap[r][c]);            }        cout << s << endl;    }}
0 0
原创粉丝点击