首页 > 代码库 > ZigZag Conversion

ZigZag Conversion

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   NA P L S I I GY   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 - 2 - 2 * i

C++代码如下:

#include<iostream>#include<string>using namespace std;class Solution {public:        string convert(string s, int nRows) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        string result;        if (nRows < 2) return s;        for (int i = 0;i < nRows;++i) {            for (int j = i;j < s.length();j += 2 * (nRows - 1)) {                result.push_back(s[j]);                if (i > 0 && i < nRows - 1) {                    if (j + 2 * (nRows - i - 1) < s.length())                        result.push_back(s[j + 2 * (nRows - i - 1)]);                }            }        }        return result;    }};int main(){    Solution s;    string ss="PAYPALISHIRING";    string sss="0123456789";    cout<<s.convert(sss,4)<<endl;}

运行结果:

ZigZag Conversion