您的位置:首页 > 其它

6. ZigZag Conversion

2016-07-19 21:29 260 查看
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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: