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

*************************************************************************************************************************************************************

其实这个就是对角线循环的问题


然后我们在一行一行地输出

string convert2(string s, int numRows) {
        if(numRows<2) return s;
        string result[numRows];
	    for(int i=0; i<s.size(); i++){
		    if(i%(numRows*2-2)<numRows)
			    result[i%(numRows*2-2)]+=s[i];
	    	else
			    result[(numRows*2-2)-i%(numRows*2-2)]+=s[i];
	    }
	s="";
	for(int i = 0; i < numRows; ++i)
        s += result[i];
    return s; 
}
string convert2(string s, int numRows) {
        if(numRows==1) return s;
        string result[numRows];
        int i=0,j,gap=numRows-2;
	    while(i<s.size()){
	    	for(j=0; i<s.size()&& j<numRows; j++){
	    		result[j]+=s[i++];
	    	}
	    		
	    	for(j=gap; i<s.size()&& j>0; j--){
	    		result[j]+=s[i++];
	    	}
	    		
	    }
	s="";
	for(int i = 0; i < numRows; ++i)
        s += result[i];
    return s; 
}
ZigZag Conversion_第1张图片

你可能感兴趣的:(ZigZag Conversion)