美文网首页
ZigZag Conversion

ZigZag Conversion

作者: violinmeng | 来源:发表于2016-06-20 11:46 被阅读25次

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)
字符串以给定的一个行数写成Z字形如下:(为了更好的易读性,需要固定的字体来展示这个图案)。

P        A        R
A     P  L     I  I
Y  A     I  H     N
P        S        G

如上图所示,返回的字符串为PARAPLIIYAIHNPSG其中numRows=4

解:

在第一行和最后一行每个字母相隔2(numRows-1),而其他的行每个2(numRows-1)之间插入了一个字母,距离前一个字母的距离为2(numRows-row-1)(row为当前行)。所以代码可写如下(C++)
class Solution { public: string convert(string s, int numRows) { if (numRows <= 1) return s; string res; for(int row = 0;row<numRows;row++){ for(auto c=s.begin()+row;c<s.end();c+=(2*numRows-2)){ res.push_back(*c); if(row!=0&&row!=numRows-1&&c+2*(numRows-row-1)<s.end()) res.push_back(*(c+2*(numRows-row-1))); } } return res; } };
时间复杂度为O(numRows
n),空间复杂度为O(1).

相关文章

网友评论

      本文标题:ZigZag Conversion

      本文链接:https://www.haomeiwen.com/subject/wtewdttx.html