[LeetCode]ZigZag Conversion

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

思考:画图,找出间隔规律。

class Solution {

public:

    string convert(string s, int nRows) {

        // IMPORTANT: Please reset any member data you declared, as

        // the same Solution instance will be reused for each test case.    

		int len=s.length();

		string s1(len,'a');

		int gap=2*nRows-2;

		int i,j,k;

	    i=0;//s1下标

		j=0;//行

		int index=0;//对应s下标

		if(nRows==1) return s;

		while(i<len)

		{

			index=j;		

			if(j==0||j==(nRows-1))

			{				

				while(index<len)

				{

					s1[i]=s[index];

					index+=gap;					

					i++;

				}

			}

			else

			{

				s1[i]=s[index];			

				while(index<len) /*内部也要判断*/

				{

					i++;

					index+=gap-2*j;

					if(index>=len) break;	

					s1[i]=s[index];

					i++;

					index+=2*j;

					if(index>=len) break;	

					s1[i]=s[index];

				}			

			}

			j++;

		}

		return s1;

    }

};

      当不满足while条件时,还要运行完while语句才会跳出循环。在此mark,祭奠我像傻子一样的一个小时。

你可能感兴趣的:(conversion)