6. ZigZag Conversion

来源:互联网 发布:暗黑破坏神2修改器mac 编辑:程序博客网 时间:2024/05/29 10:42

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

这里的zigzag排序在图像格式JPEG的存储上得到应用。

string ZigZagConversion::convert(string s, int numRows){    if (numRows <= 1) return s;    const int len = s.length();    string *str = new string[numRows];    //step控制存储的方向    int row = 0, step = 1;    for (int i = 0; i < len; ++i)    {        str[row].push_back(s[i]);        if (row == 0)        {            step = 1;        }        else if (row == numRows - 1)        {            step = -1;        }        row = row + step;    }    //重构字符串    s.clear();    for (int j = 0; j < numRows; j++)    {        s.append(str[j]);    }    delete[] str;    return s;}