6. ZigZag Conversion

来源:互联网 发布:题库系统源码 编辑:程序博客网 时间:2024/05/22 01:48

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

一道好烦的easy,首先题意就难懂233333,做法也很简单,就每一个字符新的位置放入一个重载的队列中,最后生成新的string。

class Solution {    struct num    {        char c;        int a1, a2;        bool operator < (const num& n) const{            return a1 > n.a1 || (a1 == n.a1 && a2 > n.a2);        }    };public:    string convert(string s, int numRows) {        if(numRows == 1)            return s;        priority_queue<num>pp;        int len = s.length();        for(int i = 0; i < numRows; ++ i)        {            num x;            x.c = s[i];            x.a1 = i + 1;            x.a2 = 1;            pp.push(x);        }        int nowa = numRows, nowb = 1;        int i = numRows;        while(i < len)        {            for(int j = 1; j <= numRows - 2 && i < len; ++i, ++j)            {                nowa--;nowb++;                num x;                x.c = s[i];                x.a1 = nowa;                x.a2 = nowb;                pp.push(x);            }            nowa--;nowb++;            if(i >= len) break;            for(int j = 1; j <= numRows && i < len; ++i, ++j)            {                num x;                x.c = s[i];                x.a1 = nowa;                x.a2 = nowb;                pp.push(x);                nowa++;            }            nowa--;        }        string news = "";        for(int k = 0; k < len; ++k)        {            num newc = pp.top();            news.push_back(newc.c);            pp.pop();        }        return news;    }};
0 0