[LeetCode] #6 ZigZag Conversion

it2022-05-05  128

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

程序很简单第一排和最后一排是一组公式,2*nRows-2,,其他排用另一组公式,分奇偶,公式分别是2 * (nRows - i - 1)和2 * i 。时间:29ms

代码如下:

class Solution { public: string convert(string s, int nRows) { if (nRows <= 1 || s.size() == 0) return s; string str; for (int i = 0; i < s.size() && i < nRows; i++){ int j = i, x=1; while (j < s.size()){ str += s[j]; if (i == 0 || i == nRows-1) j += 2 * nRows - 2; else{ if (x & 0x1) j += 2 * (nRows - i - 1); else j += 2 * i; x++; } } } return str; } };

转载于:https://www.cnblogs.com/Scorpio989/p/4401941.html

相关资源:LeetCode6 ZigZag Conversion

最新回复(0)