问题描述
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"
.
解决方法
这道题我一直从n阶方阵与数组索引的关系上下手,没想到这个方法这么简单。
从串的索引0开始,一直到结尾,按正序遍历,将每个字符按照第0行放一个,第1行放一个......第numRow行放一个,第numRow-1行放一个,......第0行放一个..........这种循环来放字符。用变量incre来控制行之间的来回循环,直至串尾。
本解法抓住了只需打印每一行的串,而不需要知道每个字符的绝对位置,只需要相对位置(即前后顺序对就行)这个点,从而一举解决问题。
public String convert(String s, int numRows) {
if(numRows<=1)return s;
StringBuilder[] sb=new StringBuilder[numRows];
for(int i=0;i<sb.length;i++){
sb[i]=new StringBuilder(""); //init every sb element **important step!!!!
}
int incre=1;
int index=0;
for(int i=0;i<s.length();i++){
sb[index].append(s.charAt(i));
if(index==0){incre=1;}
if(index==numRows-1){incre=-1;}
index+=incre;
}
String re="";
for(int i=0;i<sb.length;i++){
re+=sb[i];
}
return re.toString();
}
时间复杂度,0(n)