Fork me on GitHub

LeetCode 6 ZigZag Conversion(规律)

题目来源:https://leetcode.com/problems/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".

 

解题思路:

 

Zigzag:即循环对角线结构(

 

0       8       16      
1     7 9     15 17      
2   6   10   14   18      
3 5     11 13     19      
4       12       20      

 

给出代码:

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

 

posted @ 2015-12-25 19:38  伊甸一点  阅读(343)  评论(0编辑  收藏  举报