首页 > 其他 > 详细

Leetcode: ZigZag Conversion

时间:2014-11-26 22:21:22      阅读:310      评论:0      收藏:0      [点我收藏+]

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

分析:本题的难点在于找出字符串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

原文:http://www.cnblogs.com/Kai-Xing/p/4125052.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!