leetcode 题目
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"
.
这个刚开始我还懵b--什么是zig形状啊。。。。
于是我搜索了一下,原来是这样:
偶,这样啊......看着就像求一个循环结构(就是一个形状不断重复)---然后求原数组元素在新的排列规则下的位置。那就求呗(高中数学题,有没有这感觉)
然后我先求竖的:j=step;//step代表他是一个周期内的第几个元素j代表该元素在新的n个String【indes】中的index;
斜的:j=2*numRows-step;
于是代码如下:
public class Solution{
public String convert(String s,int numRows){
if(numRows==1)
return s;
int k=numRows*2-2;
String[] res=new String[numRows];
for(int i=0;i<res.length;i++){
res[i]="";
}
int step=0;
int j=0;
for(int i=0;i<s.length();i++){
step++;
if(step<=numRows){
j=step;
}else{
j=2*numRows-step;
}
res[j-1]+=subString(i,i+1);
if(ste==k)
step=0;
}
String result="";
for(String str:res){
result+=str;
}
return result;
}
}