原题链接:6. ZigZag Conversion
【思路1】
跟随 i 的下标顺序添加,将结果放在 sb[] 中,最后将 sb 拼接在一起就可以:
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, 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;
}
StringBuilder re= new StringBuilder();
for(int i=0;i<sb.length;i++)
re.append(sb[i]);
return re.toString();
}
1158 / 1158 test cases passed. Runtime: 14 ms Your runtime beats 40.21% of javasubmissions.
【思路2】
一行一行地添加,每次 gap1和 gap2都要交替变化:
public String convert(String s, int numRows) {
if (numRows < 2) return s;
StringBuilder sb = new StringBuilder();
for (int i=0; i < numRows; i++)
for (int j = i, gap = 0, gap1=(numRows-1-i)*2, gap2=i*2; j < s.length(); j += gap) {
sb.append(s.charAt(j));
gap = gap == gap1 ? gap2 : gap1;
if (gap == 0) gap = 2 * (numRows - 1);
}
return sb.toString();
}
1158 / 1158 test cases passed. Runtime: 10 ms Your runtime beats 60.85% of javasubmissions.
【思路3】
一行一行地遍历,除了第一行和最后一行以外,其他的都需要添加 secIndex:
public String convert(String s, int numRows) { //7ms
if (n < 2) return s;
char res[] = new char[s.length()];
for (int row = 0,i=0,groupCount = 2*numRows-2; row < numRows; row++) //一次加一行
for (int index = row,secIndex = groupCount-row; index < s.length();index += groupCount,secIndex += groupCount){
res[i++] = s.charAt(index);
if (row > 0 && row < numRows-1 && secIndex < s.length())
res[i++] = s.charAt(secIndex);
}
return new String(res);
}
1158 / 1158
test cases passed.
Runtime:
6 ms Your runtime beats 94.36% of javasubmissions.