题目
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 RAnd 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"
.
解题思路
解法有很多,这里采用的方法是这样的:首先算出变换之后每一行的起始地址,然后再一组一组地变换,每组元素的个数为2*numRows-2。时空复杂度均为O(n) 。
代码
public class Solution {
public String convert(String s,int numRows){
if(numRows<=1 || s.length()==0)
return s;
char[] ss=new char[s.length()];
int[] startIndex=new int[numRows];
int len=2*numRows-2;
int n=s.length()/len;
int m=s.length()%len;
startIndex[0]=0; //the start index of each row after convert
startIndex[1]=startIndex[0]+n+(m>=1?1:0);
for(int i=2;i<numRows;++i)
{
startIndex[i]=startIndex[i-1]+2*n;
if(m>=i)
++startIndex[i];
if(m>=2*numRows-i)
++startIndex[i];
}
for(int i=0;i*len<s.length();++i) //fill in the answer string group by group(2*numRows-2)
{
ss[startIndex[0]++]=s.charAt(i*len);
for(int j=1;j<numRows-1;++j)
{
if(i*len+j<s.length()) ss[startIndex[j]++]=s.charAt(i*len+j);
if(i*len+2*numRows-2-j<s.length()) ss[startIndex[j]++]=s.charAt(i*len+2*numRows-2-j);
}
if(i*len+numRows-1<s.length()) ss[startIndex[numRows-1]++]=s.charAt(i*len+numRows-1);
}
return String.valueOf(ss);
}
}
运行结果