Leetcode#6 ZigZag Conversion

来源:互联网 发布:2017中国机电贸易数据 编辑:程序博客网 时间:2024/04/28 02:22

Difficulty Easy


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"


class Solution {public:   string convert(string s, int numRows) {        int j = 0, len = s.length(),coun=0;        if(numRows==1||len==1)            return s;        string ans;        while(j<len)        {            ans =ans + s[j];            j = j + 2*numRows -2;        }        if(len>=2)        {            for(int i=1;i<=(numRows-2);i++)            {                int k =i;                while(k<len){                ans=ans + s[k];                k = k + 2*(numRows-1-i);                             if(k<len)                    ans=ans + s[k];                else                    break;                k = k + 2*i;                                }            }        }        if(len>=numRows&&len!=1){            j = numRows - 1;            while(j<len)        {            ans=ans+ s [j];            j = j + 2*numRows -2;                   }        }        cout<<ans<<endl;        return ans;        }};


0 0
原创粉丝点击