leetcode第6题ZigZag Conversion

来源:互联网 发布:剑三血痕成男捏脸数据 编辑:程序博客网 时间:2024/05/14 10:57

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


转载自:http://www.cnblogs.com/sanghai/p/3632528.html


Zigzag:即循环对角线结构(

0   8   16   1  79  1517   2 6 10 14 18   35  1113  19   4   12   20   

 

向下循环:nRows

斜角线循环:nRows-2(减去首尾两个端点)

重复

...

1
2
3
4
5
6
7
8
9
10
11
12
13
string convert(string s,int nRows){
    if(nRows == 1)return s;
    string res[nRows];
    inti = 0, j, gap = nRows-2;
    while(i < s.size()){
        for(j = 0; i < s.size() && j < nRows; ++j) res[j] += s[i++];
        for(j = gap; i < s.size() && j > 0; --j) res[j] += s[i++];
    }
    string str ="";
    for(i = 0; i < nRows; ++i)
        str += res[i];
    returnstr;
}

 

技巧:创建res[nRows]保存每一行的字符串。

           利用向下循环和对角线循环组成一个大循环。


0 0
原创粉丝点击