leetcode第六题 ZigZag Conversion (java)

java

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 text, int nRows);

convert("PAYPALISHIRING", 3) should

return "PAHNAPLSIIGYIR".

思路:列输入-->行输出,将zigzag字符串看成是字符数组,为空的位置其值为null

 

       先确定数组的列数(nRows即为数组的行数)

time=440ms

accepted

public class Solution {

public String convert(String s, int nRows) {

int length=s.length();

if(length<=nRows||nRows==1)

return s;

int updown=0,i=0,j=1,count=0,nLines=0;

while(count<length){

if(updown==0){

if(i>nRows-1){

updown=nRows-1;

i=nRows-2;

}else{

count++;

i++;

}

}

if(updown==nRows-1){

if(i<1){

updown=0;

i=0;

j++;

}else{

count++;

i--;

j++;

}

}

}

nLines=j;

System.out.println("j="+j);

char[][] zigzag=new char[nRows][nLines];

updown=0;i=0;j=0;count=0;

while(count<length){

if(updown==0){

if(i>nRows-1){

updown=nRows-1;

i=nRows-2;

j++;

}else{

zigzag[i][j]=s.charAt(count);

count++;

i++;

}

}

if(updown==nRows-1){

if(i<1){

updown=0;

i=0;

}else{

zigzag[i][j]=s.charAt(count);

count++;

i--;

j++;

}

}

}

StringBuffer sb = new StringBuffer();

for(int m=0;m<nRows;m++)

for(int n=0;n<nLines;n++){

if(zigzag[m][n]!='\0'){

sb.append(String.valueOf(zigzag[m][n]));

}

}

return sb.toString();

}

}





以上是 leetcode第六题 ZigZag Conversion (java) 的全部内容, 来源链接: utcz.com/z/393181.html

回到顶部