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

这个题目实际上是一个循环的问题,主要是通过循环规律找到字符串下标,先计算出第一个Z的V部分然后通过他们之间的下标差来计算以后字符的坐标。


public class Solution {
    	public String convert(String s, int numRows) {
		
		if(s.length()<=numRows||numRows==1)return s;
		StringBuffer stringBuffer = new StringBuffer();
		int[][] data = new int[numRows][2];
		for(int i=2;i<numRows;i++){
			
				data[i][0]=i-1;
		
				data[i][1]=2*numRows-i-1;

		}
		int index = 0;
		while(index<s.length()){
			stringBuffer.append(s.charAt(index));
			index += 2*numRows-2;
		}
		for(int i=2;i<numRows;i++){
			while(true){
				if(data[i][0]>=s.length())break;
				stringBuffer.append(s.charAt(data[i][0]));
				data[i][0]+=2*numRows-2;
				if(data[i][1]>=s.length())break;
				stringBuffer.append(s.charAt(data[i][1]));
				data[i][1]+=2*numRows-2;
				
				
			}
		}
        index = numRows-1;
        while(index<s.length()){
        	stringBuffer.append(s.charAt(index));
        	index += 2*numRows-2;
        }
		return stringBuffer.toString();
    }
}


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