第六题Z形转换,是一道找规律的题。
如果是第一行和最后一行,每两个字符中间相差2*numRows-2。
其他行,竖着的字符之间相差2*numRows-2,斜着的字符为j+2*numRows-2-2i(i为行数,j为当前竖着的字符在原字符串的位置)。
class Solution {
public String convert(String s, int numRows) {
if(s == null || s.length()==0 || numRows <=0) return "";
if(numRows == 1) return s;
int l=2*numRows-2;
StringBuilder res = new StringBuilder();
for (int i=0;i<numRows;i++){
for (int j=i;j<s.length();j+=l){
res.append(s.charAt(j));
if (i!=0 && i!=numRows-1){
int temp=j+l-2*i;
if (temp<s.length())
res.append(s.charAt(temp));
}
}
}
return res.toString();
}
}
本文介绍了一种将字符串以Z形方式排列的算法实现。该算法通过特定的数学规律来确定每个字符在Z形模式下的位置,并提供了一个Java代码示例来展示如何实现这一转换过程。
1747

被折叠的 条评论
为什么被折叠?



