ZigZag Conversion

来源:互联网 发布:北京程序员过剩 编辑:程序博客网 时间:2024/05/20 23:36

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   NA P L S I I GY   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();    }}


0 0
原创粉丝点击