首页 > 代码库 > Leetcode: ZigZag Conversion

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

分析:本题的难点在于找出字符串s中字符分布在zigzag字符串每行的规律。不难看出,s中位置满足j*(2*nRows-2)的字符被分到第一行,位置满足nRows-1+j*(2*nRows-2)的字符被分配到第nRows行。对于除第一行和第nRows行的其他行,s中位置为i+j*(2*nRows-2)和i+j*(2*nRows-2)+(nRows-1-i)的字符先后被分到第i+1行,此处i = {1,2...,nRows-2}。由上述规律,我们可以轻松写出如下代码:

class Solution {public:    string convert(string s, int nRows) {        if(nRows == 1) return s;        int n = s.length();        if(nRows >= s.length()) return s;                string result;        for(int i = 0; i < nRows; i++){            if(i == 0 || i == nRows-1){                for(int j = i; j < n; j += 2*nRows-2)                    result.push_back(s[j]);            }else{                for(int j = i; j < n; j += 2*nRows-2 ){                    result.push_back(s[j]);                    if(j+2*(nRows-1-i) < n)                        result.push_back(s[j+2*(nRows-1-i)]);                }            }        }        return result;    }};

 

Leetcode: ZigZag Conversion