LeetCode【6】. ZigZag Conversion --思路图解与java实现
一、题目例如以下:
"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”字锯齿形进行重排。
二、思路
如图。将该图形进行分区。
图一、分区图
从以上我们能够非常清晰地依据给定字符串的索引来求出其在一个“Z”型中所处的位置。是处于竖行还是斜行。是在第几排。
思路清晰,结合图及下面代码、凝视。能够非常快明确思路。
三、Java实现
public class Solution {
public String convert(String s, int numRows) {
int sl = s.length();
if(numRows<=1||sl<=numRows)
return s;
int N = (int)Math.ceil((double)sl/(2*numRows-2)); //1. 计算分区大小。最后一个区可能是充满也可能是不满。所以向上取整
int index1=0, index2=0;
int nN = 2*numRows-2; //2. 求出一分区内有多少元素。竖行是numRows个。斜行需减去头尾两个元素
StringBuffer sb = new StringBuffer();
for(int iR = 1; iR<=numRows; iR++) //3. 按行进行扫描输出
{
for(int jN = 1; jN<=N; jN++) //4. 扫描iR行的不同分区
{
//4.1. index1为第jN块的第iR行竖值索引
index1 = (jN-1)*nN + iR;
if(index1<=sl)
{
sb.append(s.charAt(index1-1));
}
//4.2. index2为第jN块的第iR行斜值索引。斜行去掉头尾两个
if((iR!=1)&&(iR!=numRows))
{
index2 = (jN-1)*nN + 2*numRows -iR;
if(index2<=sl)
{
sb.append(s.charAt(index2-1));
}
}
}
}
return sb.toString();
}
}

浙公网安备 33010602011771号