## 字符串按照Z旋转90度然后上下翻转的字形按行输出字符串--ZigZag Conversion

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 s, int numRows);

Example 1:

Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"


Example 2:

Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:

P     I    N
A   L S  I G
Y A   H R
P     I
Accepted
303,542
Submissions
970,790

    public String convert(String s, int numRows) {//ZigZag Conversion
int len=s.length();
if(numRows==1||s==null||s.equals(" ")||len<=numRows) return s;
else{
char[] result=new char[len];
char[] cs=s.toCharArray();
int cLen = 0;
int split1=2*(numRows-1);
int nDouble=len/split1;
if(len%split1==0){
cLen=(1+numRows-2)*nDouble;

}else if(len%split1<=numRows){
cLen=(1+numRows-2)*nDouble+1;
}else{
cLen=(1+numRows-2)*nDouble+(len%split1)-(numRows-1);
}

char[][] ch=new char[numRows][cLen];
int dif=split1;
for(int k=0;k<len;k++){
//                System.out.println("start++++::::"+k);
if(k%dif==0){  //up start
int t=k>0?(k/2):0;
if(k+numRows>len){
for(int j=0;j<len-k;j++){
//                            System.out.println("45-----"+j+","+t+"="+(k+j));
ch[j][t]=cs[k+j];
}
k=len-1;
break;
}else{
for(int j=0;j<numRows;j++){
//                        System.out.println("52-----"+j+","+t+"="+(k+j));
ch[j][t]=cs[k+j];
}
k=k+numRows-2;
}

}else if((k%dif==(numRows-1))){//down start
//                    System.out.println(k);
int t=k+1-numRows>0?((k+1-numRows)/2):0;
int tt=numRows-1;
if(k+numRows-2>=len){
for(int j=0;j<len-k-1;j++){
--tt;
++t;
//                            System.out.println("64-----"+tt+","+t+"="+cs[k+j+1]);
ch[tt][t]=cs[k+j+1];
}
k=len-1;
break;
}else{
for(int j=0;j<numRows-2;j++){

--tt;
++t;
//                        System.out.println("t:"+tt);
//                        System.out.println("70-----"+tt+","+t+"="+cs[k+j+1]);
ch[tt][t]=cs[k+j+1];
}
k=k+numRows-2;
//                    System.out.println("79----"+k);
}

}
}
int next=0;
for(int i=0;i<ch.length;i++){
for(int j=0;j<ch[0].length;j++){
//                     System.out.print(ch[i][j]);
if(ch[i][j]!='\u0000'){
result[next++]=ch[i][j];
}
}
}

return new String(result);
}

}

posted on 2019-04-14 00:46  Honey_Badger  阅读(...)  评论(...编辑  收藏