LeetCode-ZigZag Conversion

来源:互联网 发布:洋葱新闻 知乎 编辑:程序博客网 时间:2024/06/18 17:24

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

题意:给定一个行数,string按照行数进行之字排列,然后按照行重新组合成一个新string。
排列后的第一行元素在s中的坐标有如下的规律:
这里写图片描述

可以通过如下来获取排列后的string:
1.k=(s.length()-1)/(numRows-1)可以第一行元素最大坐标,若k为奇数,则令k=k+1,补满第一行。此处没有进行k=(s.length()-1)/(2*(numRows-1))是为了判断是否需要补满第一行。
2.根据第一行元素坐标减去或加上行数可以得到下面每行的元素。
对元素的坐标进行限制:>=0 && < s.length()。
注意最后一列,第一行两个元素右边的减去最大行等于左边的加上最大行,要去重。
需要补满的情况:
这里写图片描述

不需要对首行元素进行补满:

这里写图片描述
代码如下:

string convert(string s, int numRows) {    if(numRows==1)    {        return s;    }    int slen=s.length();    if(slen<=numRows)    {        return s;    }    string ret;    int k=(slen-1)/(numRows-1);    if(k%2!=0)    {        k=k+1;    }    for(int i=0;i<numRows;i++)    {        for(int j=0;j<=k;j+=2)        {            int temp=j*(numRows-1);            int templ=(j-2)*(numRows-1);            if(temp-i>=0&&temp-i!=templ+i&&temp-i<slen)            {                ret+=s[temp-i];            }            if(temp+i!=temp-i&&temp+i<slen)            {                ret+=s[temp+i];            }        }    }    return ret;       }
0 0
原创粉丝点击