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

很麻烦的找规律的题。

1.规律是锯齿状的,|/|/|/ ...

2.找到规律后依然很难弄。最简单的方法是申请个二维数组,填进去,再读出来。仔细观察后发现每一行字母下表有规律,利用规律计算可以减少空间浪费。最后把任务分成首行、中间行、尾行三部分处理完。

class Solution {
public:
    string convert(string s, int nRows) {
        if(nRows == 0)return "";
        if(nRows == 1)return s;
        
        int num = s.length();
        int group = 2*nRows -2;
        int flag = 0;
        int n_group;
        if(num%group == 0) n_group =num/group;
        else n_group =num/group+1;
        
        string re = "";
        for(int i = 0 ; i < n_group ; i++)
        if(i*group<num)re += s[i*group];
        for(int i = 1 ; i < nRows -1;i++)
        {
            for(int j = 0 ;j <n_group ;j++)
            {
                if(j *group + i < num) re += s[j *group + i];
                if((j+1) *group - i < num) re += s[(j+1) *group - i ];
            }
        }
        for(int i = 0 ; i < n_group ; i++)
        if(group*i + nRows-1 <num)re+=s[group*i + nRows-1];
        return re;
    }
};

 

posted on 2014-03-05 22:11  pengyu2003  阅读(125)  评论(0编辑  收藏  举报

导航