LeetCode-006 ZigZag Conversion

来源:互联网 发布:尼康失真控制数据 编辑:程序博客网 时间:2024/06/06 05:26

Description

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

Analyse

这其实是一道字符串题目,但这道题有点毛病,乍一看不懂它的要求是什么,我们根据标题可推理出,它是想让我们把字符串按照类似拉链一样排列,也就是“Z”字型排列。举个例子:
画了个图,不好看请见谅(捂脸)
这里写图片描述
你会发现这样一个规律(n>1),上面的数字为字符标号,然后我们就可以直接根据这个规律来写代码啦。
规律为:当字符的下标不超过字符串长度时,每两个竖列的对应横排的数相差(2n-2),然后中间的数按照公差为2这样的速率向下变动,直到这个变化为0,那么就完成了。也就是,第一列的公差为(2n-2),第二列的公差为(2n-4)和2交替进行,然后按照这个规律向下变化。
最后一行跟第一行需要拿出来特殊处理,其它的可以一并处理。
对于n=1的情况,输出字符串为原字符串,需要特殊处理。
算法结束。

Code

class Solution {public:    string convert(string s, int numRows) {        int len=s.length();        string ans="";        if (numRows==1) return s;        for (int i=0;i<numRows;i++) {            int p=i;            while (p<len) {                //最后一行的判断                if (i!=numRows-1) {                    ans=ans+s[p];                    p=p+2*(numRows-i-1);                }                if (p>=len) break;                //第一行的判断                if (i!=0) {                    ans=ans+s[p];                    p=p+2*i;                   }            }        }        return ans;    }};