ZigZag Conversion

来源:互联网 发布:淘宝可以改会员名吗 编辑:程序博客网 时间:2024/05/08 18:14

The string "PAYPALISHIRING" is written in azigzag pattern on a given number of rows like this: (you may want to displaythis pattern in a fixed font for better legibility)

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



And thenread line by line: "PAHNAPLSIIGYIR"

Write the code that will take a string and make this conversiongiven a number of rows:

stringconvert(string text, int nRows);

convert("PAYPALISHIRING",3) should return "PAHNAPLSIIGYIR".


class Solution {public:    string convert(string s, int nRows) {        if (nRows == 1) {            return s;        }        string *arr = new string[nRows];        for (int i=0; i<nRows; ++i){            arr[i]= "";        }        int len = s.length();        int step[2]={1,-1};        for (int i=0,j=0; i<len; ++i) {            int stepPos = i/(nRows-1)%2;            arr[j]+=s[i];            j+=step[stepPos];        }        s="";        for (int i=0; i<nRows; ++i){            s+=arr[i];        }        delete []arr;        return s;    }};


 

And thenread line by line: "PAHNAPLSIIGYIR"

Write the code that will take a string and make this conversiongiven a number of rows:

stringconvert(string text, int nRows);

convert("PAYPALISHIRING",3) should return "PAHNAPLSIIGYIR".

0 0