标签:字符串
整体的思路是遍历字符串,遍历过程中将每行都看成新的字符串构成字符串数组,最后再将该数组拼接起来即可
如果 numRows=1numRows=1numRows=1 则说明当前字符串即为结果,直接返回
否则整个字符串需要经历,向下向右,向下向右,这样的反复循环过程,设定 downdowndown 变量表示是否向下,loclocloc 变量表示当前字符串数组的下标
如果 downdowndown 为 truetruetrue,则 loc+=1loc+=1loc+=1,字符串数组下标向后移动,将当前字符加入当前字符串中
如果 downdowndown 为 falsefalsefalse,则表示向右,则 loc−=1loc-=1loc−=1,字符串数组下标向前移动,将当前字符加入当前字符串中
时间复杂度:O(n)O(n)O(n),nnn为字符串s的长度
class Solution {
public String convert(String s, int numRows) {
int n =s.length(),r=numRows;
if(r==1||r>=n){
return s;
}
StringBuffer [] mat =new StringBuffer[r];
for(int i=0;i<r;i++){
mat[i] =new StringBuffer();
}
for(int i=0,x=0,t=r*2-2;i<n;i++){
mat[x].append(s.charAt(i));
if(i%t<r-1){
++x;
}else{
--x;
}
}
StringBuffer ans =new StringBuffer();
for(StringBuffer row:mat){
ans.append(row);
}
return ans.toString();
}
}