题目:
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 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”.


本题复杂度为easy,主要问题就是把测试用例想清楚。主要就是不要忘了在第十五行记得判断​​temp<size​

public class Solution {
public String convert(String s, int numRows) {
int size = s.length();
char[] ans=new char[size];
//require
if(numRows<=1)
return s;
int k=0,j=0;
//invariant
for(int i=0;i<numRows;i++){
j=i;
while(j<size){
ans[k++]=s.charAt(j);
int temp = j+(numRows-i-1)*2;
if(i!=0&&i!=numRows-1&&temp<size)
ans[k++]=s.charAt(temp);
j+=numRows*2-2;
}
}
//ensure
return String.valueOf(ans);
}
}

另外,本题解决完后,会给出运行时间。上面的代码中的size,我以前用的是​​s.length()​​,可以看到修改前后的效率提升:

修改前:

[LeetCode]ZigZag Conversion_测试用例


修改后:

[LeetCode]ZigZag Conversion_运行时间_02

从图中可以很残酷地看到朴素的思想得到的结果是效率垫底。等我想到了更好的提升效率的办法再demonstrate。