ZigZag Conversion算法

来源:互联网 发布:新浪博客做淘宝客网站 编辑:程序博客网 时间:2024/05/22 06:35

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


依据题意,就是给出一串序列,这个序列是Z字形排序的,具体的行数将会在一开始的时候给出,我们需要做的就是把它转化成正常排序的序列


class Solution {public:    string convert(string s, int numRows) {        string a[numRows];        int length = s.size();        int k = 0,row = 0;        if(numRows == 1) return s;        if(numRows == 2) {            for(int i = 0; i < length; i++){                if(i % 2 == 0)                    a[0].push_back(s[i]);                else                    a[1].push_back(s[i]);            }            return a[0]+a[1];        }        for(int i = 0; i < length; i++){            if(k % 2 == 0){                a[row].push_back(s[i]);                row++;                if(row == numRows){                    row = numRows -2;                    k++;                }            }            else {                                a[row].push_back(s[i]);                row--;                if(row <= 0) {                    row = 0;                    k++;                }            }                                }        string sum;        for(int i = 0; i < numRows; i++)            sum+=a[i];        return sum;    }};

具体的思想就是一开始创建numRows个string,然后把s里面的值逐个分配到相对应行数的string里面,最后再把所有string拼在一起,return出去。

其中重点说一下参数k,k可以作为单个string里面的下标,即a[row][k],也是判断当前序列走势的关键

P A  Y
这种情况,走势为朝下,k为偶数



   A   P Y
这种情况,走势为朝上,k为奇数



我以此作为一个整体的走势单位

P    A P   Y  
所以,k为偶数,此时行数row要逐个递增,增加到等于总行书numRows时,就要换另一种走势,

   k为奇数,此时行数row要逐个递减,增加到小于等于0时,就算一个完成一个单位。

最后完成所有s里面的值的分配。


当然,以上是针对行数大于2的情况。

当行数等于1时,直接返回s。当行数等于2时,根据奇偶分配s里面的值到两个string中。

原创粉丝点击