leetcode6 ZigZag Conversion

来源:互联网 发布:西安中国银行软件中心 编辑:程序博客网 时间:2024/05/29 14:14

这个leetcode上的题目写的就是太简单了,就是简单一句话加上一个测试用例就完事了,不严谨,总是理解错,这个让我很闹心啊.

大概题意就是,将字符串排列成连续的折线,就像是很多个N连在一起那种,之后再按行相加然后返回就OK了.


仔细观察图形可以发现,第一行和最后一行是可直接循环相加的,不需要加中间的那些字符,字符串的循环周期为

crcle = (numRows-1)*2;

比如说举一个numRows为6的例子,crcle就是10,第一行和最后一行直接以10为周期循环相加就OK了,但是中间的四行就必须得每次循环加两个字符,一个是循环周期中的字符,另外一个是中间斜线上的字符,他们中间有对应的规律就是1-9,2-8,

3-7,4-6,其实就是crcle-i,每次循环的时候都要加crcle那么就是k*crcle+crcle-1(k=0,1,2,3,4......).我们只需将表达式变成这样就OK了.


代码:

#include<stdio.h>#include<iostream>#include<string.h>#include<algorithm>using namespace std;class Solution {public:    string convert(string s, int numRows) {            int i,j,len;    int crcle;    string strtemp = "";    len = s.capacity();    crcle = numRows+1;    if(numRows == 1 || numRows >= len)     {        return s;        }        crcle = (numRows-1)*2;  for(i=0;i<numRows;i++)  {  for(j=i;j<len;j+=crcle)  {  strtemp+=s[j];  if(i==0||i==numRows-1)  continue;  else if((j+crcle-(2*i))<len)  strtemp+=s[j+crcle-(2*i)];  }  }    return strtemp;    }};int main(){string result = "PAHNAPLSIIGYIR";string s= "PAYPALISHIRING";int num = 3;Solution test;cout<<result<<endl;result = test.convert(s,num);cout<<result<<endl;return 0;}


0 0
原创粉丝点击